第十六天:状态不好,偷懒了。明天认真打卡!

本文介绍了解决二叉树最大深度、最小深度及完全二叉树节点计数的问题,通过递归方法实现了这三种算法。针对完全二叉树节点计数问题,提出了一种高效算法,通过检查最左侧和最右侧子树高度来判断是否为完全二叉树。
  1. Maximum Depth of Binary Tree

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

尝试了半天深度搜索遍历方法(广度搜索遍历就很简单了),都不成功…所以偷个懒,写一个递归放上来吧!

2.Minimum Depth of Binary Tree

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

3.Count Complete Tree Nodes

这个算法必须掌握!通过看最左和最右边level数量是否相等,来判断是否为完全二叉树。如果是,那么直接乘方就能知道个数啦!如果不是,只能一个一个数(最后一行return)。

class Solution {
    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        int leftCount = 1, rightCount = 1;
        TreeNode tmpl = root, tmpr = root;
        while(tmpl.left != null){
            tmpl = tmpl.left;
            ++leftCount;
        }
        while(tmpr.right != null){
            tmpr = tmpr.right;
            ++rightCount;
        }
        if(leftCount == rightCount){
            return (int) Math.pow(2, leftCount) - 1;
        }
        return 1 + countNodes(root.left) + countNodes(root.right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值