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

104.二叉树的最大深度

思路:递归法,采用后序遍历计算树的高度。先求左子树的深度,再求右子树的深度,最后取左右深度最大的数值再+1(中间节点) ,得到根节点的树的深度。

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

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; 
    }
}

111.二叉树的最小深度

思路:最小深度与最大深度不同之处在于,最小深度需要考虑左右子树为空的情况。左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度;右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。如果左右子树都不为空,返回左右子树深度最小值 + 1 。

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

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

思路:分两种情况。满二叉树,可以直接用 2^树深度 - 1 来计算;最后一层叶子节点未满,可以分别递归左孩子和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,回到第一种。

class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        TreeNode left = root.left;
        TreeNode right = root.right;
        int leftDepth = 0, rightDepth = 0; 
        while (left!=null) { 
            left = left.left;
            leftDepth++;
        }
        while (right!=null) { 
            right = right.right;
            rightDepth++;
        }
        if (leftDepth == rightDepth) {
            return (2 << leftDepth) - 1; 
        }
        int leftNum = countNodes(root.left);
        int rightNum = countNodes(root.right);
        int result = 1+leftNum+rightNum;
        return result;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值