算法训练营第十六天|104.二叉树的最大深度、559.n叉树的最大深度、111.二叉树的最小深度、222.完全二叉树的节点个数

64 阅读1分钟

104. 二叉树的最大深度

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

559. N 叉树的最大深度

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

111. 二叉树的最小深度

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null)return 0;
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);

        // 左为空,右不为空
        if(root.left == null && root.right != null){
            return 1 + rightDepth;
        }
        // 右为空,左不为空
        if(root.left != null && root.right == null){
            return 1 + leftDepth;
        }
        // 左右都不为空
        int res = 1 + Math.min(leftDepth, rightDepth);
        return res;
    }
}

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

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