1、根据逆波兰表示法,求表达式的值。

有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:

输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:

输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6
示例 3:

输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
输出: 22
解释: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

pub lic static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = 5;
        String[] str = new String[N];
        while (sc.hasNext()) {
            int i = 0;
            while (i < N) {
                str[i] = sc.nextLine();
                i++;
            }
            int len = N;
            Stack<Integer> stack = new Stack<>();
            for (i = 0; i < len; i++) {
                if (str[i].equals("+") || str[i].equals("-") || str[i].equals("*") || str[i].equals("/")) {
                    int num2 = stack.pop();
                    int num1 = stack.pop();
                    stack.push(Caculate(num1, num2, str[i]));
                } else {
                    int number = Integer.parseInt(str[i]);
                    stack.push(number);
                }
            }
            System.out.println(stack.pop());
        }

    }

    private static Integer Caculate(int num1, int num2, String operator) {
        switch (operator){
            case "+": return num1 + num2;
            case "-": return num1 / num2;
            case "*": return num1 * num2;
            case "/": return num1 / num2;
            default:
                return 0;
        }
    }
}

2、求完全二叉树的节点个数,并分析复杂度

递归

private static int fun(TreeNode root) {
    if(root!=null){
        return 1+fun(root.left)+fun(root.right);
    }else{
        return 0;
    }
}
  • 时间复杂度:O(N)。
  • 空间复杂度:O(d) = O(log N),其中 d指的是树的的高度,运行过程中堆栈所使用的空间。

非递归

public static int countNodes(TreeNode root) {
    if(root==null)return 0;
    //mostLeftLevel(root,1)的值为:3
    return bs(root,1,mostLeftLevel(root,1));
}
//node为当前节点,level是其层数,h是树的深度
public static int bs(TreeNode node, int level, int h){
    //h=3
    if(level==h)return 1;
    if(mostLeftLevel(node.right,level+1)==h)
        //1<<(h=level),1向左移x位,就是2的x次幂
        return (1<<(h-level))+bs(node.right,level+1,h);
    else return (1<<(h-level-1))+bs(node.left,level+1,h);


}
public static int mostLeftLevel(TreeNode node, int level){
    while(node!=null){
        level++;
        node=node.left;
    }
    return level-1;
}

复杂度:O((logN)^2)

3、坐标系中有一个球桌,四个角坐标:
(0,0), (0,4), (2,4), (2,0)
一颗球在(1,1),请问从哪些角度可以射入洞内(可无限次碰撞)?

解答:
一般想法是将球镜像对称,但这道题是把洞镜像对称
将这个桌面在这个平面无限延展,可类比成无限张球桌紧密放置
那么每一个和球洞的连线都是合法路径