104.二叉树最大深度105.最小深度559.N叉树最大深度222.完全二叉树节点数

145 阅读1分钟

104.二叉树最大深度

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

105.最小深度

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

559.N叉树最大深度

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

222.完全二叉树节点数

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