代码随想录day14:二叉树part3,深度/高度,完全二叉树节点个数

day14:二叉树part3,高度/深度,完全二叉树节点个数

559.N 叉树的最大深度

class Solution {
    public int maxDepth(Node root) {
        // 空节点
        if (root == null) return 0;
        // 叶子节点
        List<Node> children = root.children;
        if (children.size() == 0) return 1;
        // 有孩子的节点
        int max = Integer.MIN_VALUE;
        for (Node child : children) {
            int depth = maxDepth(child);
            if (depth > max)
                max = depth;
        }
        return max + 1;
    }
}

111.二叉树的最小深度

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        // 左右孩子都不为空
        else if (root.left != null && root.right != null)
            return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
        // 左右孩子中有空,需要算非空孩子的深度,空节点返回0,加上不影响
        // 把左右孩子其中一个为空 和 两个都为空(叶子节点return 1) 合并了
        else return minDepth(root.left) + minDepth(root.right) + 1;
    }
}

迭代法待更新

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

当作普通二叉树来处理

其实是后序遍历的思路

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

利用完全二叉树性质:

  1. 完全二叉树分别递归左孩子,和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后可以利用满二叉树公式计算节点个数
  2. 递归向左遍历的深度等于递归向右遍历的深度,可以判断是否是满二叉树
class Solution {
    /**
     * 针对完全二叉树的解法
     *
     * 满二叉树的结点数为:2^depth - 1
     */
    public int countNodes(TreeNode root) {
        return count(root);
    }

    public int count(TreeNode root) {
        if (root == null) return 0;
        TreeNode left = root.left;
        TreeNode right = root.right;
        // 初始为 0 为了下面计算公式方便
        int leftDepth = 0, rightDepth = 0;
        while (left != null) {
            left = left.left;
            leftDepth++;
        }
        while (right != null) {
            right = right.right;
            rightDepth++;
        }
        if (leftDepth == rightDepth)
            // (2 << 1) 相当于2^2,所以leftDepth初始为0
            return (2 << leftDepth) - 1;
        
        return count(root.left) + count(root.right) + 1;
    }
}
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值