代码随想录算法训练营第16天|104.二叉树的最大深度 、559.n叉树的最大深度 、111.二叉树的最小深度 、222.完全二叉树的节点个数

84 阅读1分钟

今日内容: 

●  104.二叉树的最大深度  559.n叉树的最大深度

●  111.二叉树的最小深度

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

104. 二叉树的最大深度

可以用递归,也可以用迭代法,下面是递归法

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

559. N 叉树的最大深度

跟上一道题思路一样

class Solution {
    public int maxDepth(Node root) {
        if(root == null)return 0;
        int max = 0;
        for(Node node : root.children) {
            max = Math.max(max, maxDepth(node));
        }
        return 1+max;
    }
}

111. 二叉树的最小深度

迭代法也可以做,递归法思路差别比较大

class Solution {
    public int minDepth(TreeNode root) {
        int res = Integer.MAX_VALUE;
        if(root == null)return 0;
        int lDepth = minDepth(root.left);
        int rDepth = minDepth(root.right);

        if(root.left == null && root.right != null) {
            return 1 + rDepth;
        }
        if(root.left != null && root.right == null) {
            return 1 + lDepth;
        }
        return 1 + Math.min(lDepth, rDepth);
    }
}

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

class Solution {
    public int countNodes(TreeNode root) {
        //通过右子树的高度来判断,分别判断是否等于height - 1和height - 2
        int height = getHeight(root);
        if(height == 0)return 0;
        if(height == 1)return 1;
        //说明左子树是完美二叉树
        if(getHeight(root.right) == height - 1) {
            return (1 << (height - 1)) + countNodes(root.right);
        } else {
            return (1 << (height - 2)) + countNodes(root.left);
        }
    }
    private int getHeight(TreeNode root) {
        return root == null?0:1+getHeight(root.left);
    }
}