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.

FIND A MORE EFFICIENT CODE!!!

Analyse: 

1. do level traversal, count and add up the node(s) at each level.

    NA:  TIME LIMIT EXCEEDED

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int countNodes(TreeNode* root) {
13         if(!root) return 0;
14         queue<TreeNode* > qu;
15         qu.push(root);
16         int result = 0;
17         while(!qu.empty()){
18             int n = qu.size();
19             result += n;
20             while(n--){
21                 TreeNode* temp = qu.front();
22                 qu.pop();
23                 if(temp->left) qu.push(temp->left);
24                 if(temp->right) qu.push(temp->right);
25             }
26         }
27         return result;
28     }
29 };
View Code

 

2. Continuously judge whether the left level and right level are equal. If they are equal, return 2^level - 1; If not, compute 1 + nodes(left) + nodes(right).

    Runtime: 164ms.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int countNodes(TreeNode* root) {
13         if(!root) return 0;
14         
15         int leftLevel = 1, rightLevel = 1;
16         TreeNode* temp = root->left;
17         while(temp){
18             leftLevel++;
19             temp = temp->left;
20         }
21         temp = root->right;
22         while(temp){
23             rightLevel++;
24             temp = temp->right;
25         }
26         
27         if(leftLevel == rightLevel) 
28             return (1 << leftLevel) - 1;
29         
30         return 1 + countNodes(root->left) + countNodes(root->right);
31     }
32 };

 

posted @ 2015-08-03 11:12  amazingzoe  阅读(141)  评论(0编辑  收藏  举报