[Leetcode] Count Complete Tree Nodes

Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
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 2hnodes inclusive at the last level h.

对于这个问题的一个快速解法是统计当前树的右边界和左边界的长度,如果是相等的那么就会可以知道当前为满二叉树,节点个数为$2^{height-1}-1$个。如果不像想等,则对左右子树进行相同的操作根据完全二叉树的特点,左右子树当中肯定有一课时满二叉树,所以问题规模看起来减半。

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     private int leftdepth(TreeNode root){
12         if(root==null) return 0;
13         return leftdepth(root.left)+1;
14     }
15     private int rightdepth(TreeNode root){
16         if(root == null) return 0;
17         return rightdepth(root.right)+1;
18     }
19     
20     public int countNodes(TreeNode root) {
21         if(root==null) return 0;
22         int ldepth = leftdepth(root.left)+1;
23         int rdepth = rightdepth(root.right)+1;
24         if(ldepth==rdepth){
25             //for the bit operation, the brackets are needed to clear out the computation priority or computation order.
26             // If the below code is written as 1<<depth -1, the  the result is wrong.
27             return (1 << ldepth) -1;
28         }else{
29             return countNodes(root.right)+countNodes(root.left)+1;
30         }
31     }
32 }

复杂度分析:

最好的情况是满二叉树的情况复杂度为2*logN

其次,如果最后一层只有一半的元素,那么计算量为:logN+(logN-1)+(logN-1+logN-1)+(logN-2+logN-2)

考虑最坏的情况是最后一层少了一个元素:

首先当前更节电为root时,可以得到左右子树高度不一样,下一步左边的子树一定是满的,但是右边的子树可以看作一个比较小规模的问题,也就是高度减一

H+H-1+2*(H-1)=4H-3

总的计算量变为了

$\sum_{i=1}^{i=height}(4H-3)$

显然复杂度为$O(H^2)$

这个$O(H^2)$,即$O((LogN)^2)$是远小于$O(N)$的,所以总体的复杂度降低了不止一半

转载于:https://www.cnblogs.com/deepblueme/p/4740495.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值