1. 程式人生 > >leetode(NOWCODER)---(minimum-depth-of-binary-tree,evaluate-reverse-polish-notation)

leetode(NOWCODER)---(minimum-depth-of-binary-tree,evaluate-reverse-polish-notation)

minimum-depth-of-binary-tree

時間限制:1秒 空間限制:32768K 熱度指數:90824
本題知識點: 樹
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution { //注意最小深度的定義,必須是根到葉子節點,必須到葉子節點!! public int run(TreeNode root) { if(root == null){ return 0; } int l = run(root.left); int r = run(root.right); if(l==0 || r==0){ return l+r+1; } return Math.min
(l, r) + 1; } }

evaluate-reverse-polish-notation

時間限制:1秒 空間限制:32768K 熱度指數:73409
本題知識點: 棧 leetcode
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:

[“2”, “1”, “+”, “3”, “*”] -> ((2 + 1) * 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

import java.util.*;

public class Solution {
    public int evalRPN(String[] tokens) {
        if(tokens == null || tokens.length == 0){
            return 0;
        }
        ArrayDeque<String> stack = new ArrayDeque<String>();
        for(int i = 0; i < tokens.length; i++){
            if(isOperand(tokens[i])){
                int x = Integer.valueOf(stack.pop());
                int y = Integer.valueOf(stack.pop());
                stack.push(calculate(y, x, tokens[i])+"");
            }else{
                stack.push(tokens[i]);
            }
        }
        return Integer.valueOf(stack.pop());
    }
    private boolean isOperand(String s){
        //筆者發現,把下面的equals換成indexOf就過不了。。。
        if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
            return true;
        }
        return false;
    }
    private int calculate(int x, int y, String operand){
        if(operand.equals("+")){
            return x + y;
        }else if(operand.equals("-")){
            return x - y;
        }else if(operand.equals("*")){
            return x * y;
        }else{
            return x / y;
        }
    }
}