算法二叉树第一天简单记

  1. 新手做题过程中要注意的点:要看做题质量(原画评论如下图), 不要太在意运行时间 要学会自己分析复杂度, 不要追求一行流

2. 递归的时候 不要去想每一步的细节,否则就变成了计算机了。而是要想每一步的结果,剩下的就交给数学归纳法就好了。这也是不容易被绕进去的关键。

3. 递归有两种写法,一种是 「归」的过程中做计算,个人觉得比较易懂;还有一种是在「递」的过程中 通过维护一个全局变量的方式 来做计算(暂时我还觉得有点复杂)。 所以目前为止两道练习题都是用的第一种方式。

思路都是 自下而上 「归」的过程中来做计算。

Leetcode 111: https://leetcode.com/problems/minimum-depth-of-binary-tree/submissions/1654259155/

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null){return 0;}
        if(root.right == null){
            return minDepth(root.left) + 1;
        }
        if(root.left == null){
            return minDepth(root.right) + 1;
        }
        return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }
}

Leetcode 104: https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){return 0;}
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

评论

留下评论