222. 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 2h nodes inclusive at the last level h.

 

 

 1 class Solution {
 2 public:
 3     int countNodes(TreeNode* root) {
 4     
 5         if (root == NULL) return 0;
 6         int lh = 0;
 7         int rh = 0;
 8         auto l = root;
 9         auto r = root;
10         while(l!=NULL) {lh++;l=l->left;}
11         while(r!=NULL) {rh++;r=r->right;}
12         if (lh==rh) return pow(2,lh)-1;
13         return 1 + countNodes(root->left) + countNodes(root->right);
14     return 0;
15     }
16 };

 

 

 

 

 

 

最简单的办法是遍历 粗暴遍历会超时

直接遍历每一个节点是不现实的,所以必须通过完全二叉树的特点来计算,我们可以想到,除了最下的那一层,其余的部分,都是满二叉树,这样我们首先可以判断当前的二叉树是不是满二叉树,判断的方法是判断树最左和最右两边的长度是否相等,如果相等就可以直接计算,如果不等就进入递归,分别计算左右两颗子树,知道只有一个节点的时候就停止。
因为完全二叉树进行左右分割之后,很容易就会出现满二叉树,所以节省了大量的遍历节点的时间


 
 
 
 
 1 class Solution {
 2     public int countNodes(TreeNode root) {
 3         if(root==null) return 0;
 4         int l = count_l(root);
 5         int r = count_r(root);
 6         if(l==r) return (1<<l)-1;
 7         return 1 + countNodes(root.left) + countNodes(root.right);
 8         
 9     }
10     private int count_l(TreeNode root){
11         if(root == null) return 0;
12         int cnt = 0;
13         while(root!=null){
14             cnt+=1;
15             root =root.left;
16         }
17         return cnt;
18     }
19     private int count_r(TreeNode root){
20         if(root == null) return 0;
21         int cnt = 0;
22         while(root!=null){
23             cnt+=1;
24             root = root.right;
25         }
26         return cnt;
27     }
28 }

 

posted @ 2018-02-05 21:15  乐乐章  阅读(127)  评论(0编辑  收藏  举报