代码随想录训练营第十六天 | 二叉树

今天是第十六天,继续二叉树方面的递归练习

104. 二叉树的最大深度

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

    
}

这道题一直递归直到触碰到叶子。

 

111. 二叉树的最小深度

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

和上一道题的思路一样,只是要确定如果一棵树只有一颗子树为空的话,要顺着不为空的那颗子树往下递归。

 

222. 完全二叉树的节点个数

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

这题和前两题一样,为啥是medium

今天的都是二叉树简单的递归应用,明天的难度就上来了

posted @ 2022-10-28 14:11  小猫Soda  阅读(20)  评论(0)    收藏  举报