222. Count Complete Tree Nodes

二叉树基本:

一棵深度为k的二叉树,如果它有2k-1个结点,那么就是一棵满二叉树 full binary tree

一棵深度为k的二叉树,如果它k-1层都是满二叉树,只有最后一层不满,叫做complete binary tree。一个有n个结点的完全二叉树,层高为log2N+1,最后一层上可能有1个到2k-1个结点. 总节点数至少为2k-1个,最多有2k-1个。

 

这道题的思路就是,

先算出只沿着最左边一路向下走的深度(也就是这棵树的深度),和只沿着最右侧走的深度,结果可能是这棵树的深度或者这棵树深度-1。

如果左右相等,这就是一颗满二叉树,所以节点数为2k-1,当然可以写成(1 << k).

如果不相等,那就等于左子树的节点数+右子树的节点数+1(即递归)

 

 1     public int countNodes(TreeNode root) {
 2         if(root == null) {
 3             return 0;
 4         }
 5         int left = leftCnt(root.left);
 6         int right = rightCnt(root.right);
 7         if(left == right) {
 8             return (1 << (left + 1)) - 1;
 9         } else {
10             return countNodes(root.left) + countNodes(root.right) + 1; 
11         }
12     }
13     
14     private int leftCnt(TreeNode root) {
15         if(root == null) {
16             return 0;
17         }
18         return leftCnt(root.left) + 1;
19     }
20     
21     private int rightCnt(TreeNode root) {
22         if(root == null) {
23             return 0;
24         }
25         return rightCnt(root.right) + 1;
26     }

 时间复杂度是O(log(n)^2)。

posted @ 2016-07-26 01:59  warmland  阅读(174)  评论(0编辑  收藏  举报