#leetcode#Count Complete Tree Nodes

</pre>Given a <span style="font-weight:700">complete</span> binary tree, count the number of nodes.<p></p><p style="margin-top:0px; margin-bottom:10px; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px"><span style="font-weight:700"><span style="">Definition of a complete binary tree from <a target=_blank target="_blank" href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" style="color:rgb(0,136,204); text-decoration:none; background:0px 0px">Wikipedia</a>:</span></span><br style="" /></p><p>In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2<span style="position:relative; font-size:10.5px; line-height:0; vertical-align:baseline; top:-0.5em">h</span> nodes inclusive at the last level h.</p><p>遇到这题第一反应是BFS, 数一遍就知道了, O(n),最基础的解法</p><p>再怎么减小复杂度呢?</p><p>比O( n ) 小, 也就是 O(logn)了, 所以要往二分的方向去想,</p><p>对于complete binary tree, 最底层的node都是先尽量填满左边的坑, 也就是说如果左子树的高度等于右字数的高度,那么左子树是满员的, 节点个数为2^leftHeight - 1,加入结果, 下一步循环右子树; 如果左右子树高度不等, 则肯定是右子树高度小于左子树, 右字数满员, 节点个数是<span style="color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px">2^rightHeight - 1, 加到结果中, 下一步循环左子树。 不要忘记加 root 的个数 + 1。</span></p><p><span style="color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px"></span></p><p><span style="font-family:Helvetica Neue,Helvetica,Arial,sans-serif; color:#333333"><span style="font-size:14px; line-height:30px"><strong>注意对左右子树高度为0情况的讨论, 2的零次方是1, 所以要特殊处理。</strong></span></span></p><p></p><p></p><pre name="code" class="java">/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int countNodes(TreeNode root) {
        int res = 0;
            
        TreeNode node = root;
        while(node != null){
            res++;
            int leftDepth = getDepth(node.left);
            int rightDepth = getDepth(node.right);
            if(leftDepth == rightDepth){
                res = leftDepth == 0 ? res : res + (1 << leftDepth) - 1;
                node = node.right;
            }else{
                res = rightDepth == 0 ? res : res + (1 << rightDepth) - 1;
                node = node.left;
            }
        }
        
        return res;
    }
    
    private int getDepth(TreeNode root){
        if(root == null)
            return 0;

        return getDepth(root.left) + 1;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值