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)$的,所以总体的复杂度降低了不止一半