代码随想录第十六天

内容:

  1. 二叉树的最大深度(104) N叉树的最大深度(559)
  2. 二叉树的最小深度(111)
  3. 完全二叉树的节点个数(222)

1.二叉树的最大深度 N叉树的最大深度

难度:🔥🔥🔥

建议:什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式,优先掌握递归

1.1 思路分析

本题使用后序遍历(左右中)求根节点的高度,即二叉树的最大深度。

N叉树的最大深度思路与之相似。

1.2 代码实现

二叉树的最大深度

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;//返回子树的高度给上一层
    }
}

N叉树的最大深度

class Solution {
    public int maxDepth(Node root) {
        if (root == null) {
            return 0;
        }
        int depth = 0;
        if(root.children != null) {
            for (int i = 0; i < root.children.size(); i++) {
                depth = Math.max(depth, maxDepth(root.children.get(i)));
            }
        }
        return depth + 1;
    }
}
1.3 注意事项
1.4 收获总结

2.二叉树的最小深度

难度:🔥🔥

建议:和最大深度 看似差不多,其实差距还挺大,有坑,优先掌握递归

2.1 思路分析

最小深度是从根节点到最近叶子节点的最短路径上的节点数量

2.2 代码实现
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) {
            return rightHeight + 1;
        }
        if (root.right == null) {
            return leftHeight + 1;
        }
        int result = Math.min(leftHeight,rightHeight);

        return result + 1;
    }
}
2.3 注意事项
2.4 收获总结

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

难度:🔥🔥🔥

建议:需要了解,普通二叉树 怎么求,完全二叉树又怎么求。优先掌握递归

3.1 思路分析

我们递归寻找完全二叉树的满二叉树。

如图:

222.完全二叉树的节点个数
3.2 代码实现

普通二叉树递归

class Solution {
    public int countNodes(TreeNode root) {     
		//递归
		 if (root == null) {
            	return 0;
        }
        int leftNum = countNodes(root.left);
        int rightNum = countNodes(root.right);
        return leftNum + rightNum + 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;
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
}
3.3 注意事项
3.4 收获总结
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值