222. 完全二叉树的节点个数

 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 {
12     vector<int> ans;
13 public:
14     int countNodes(TreeNode* root) 
15     {
16         if(!root) return 0;
17         queue<TreeNode*> q;
18         q.push(root);
19         while(!q.empty())
20         {
21             int n = q.size();
22             for(int i = 0;i < n;i ++)
23             {
24                 TreeNode* temp = q.front();
25                 q.pop();
26                 ans.push_back(temp->val);
27 
28                 if(temp->left) q.push(temp->left);
29                 if(temp->right) q.push(temp->right);
30             }
31         }
32         return ans.size();
33     }
34 };

 

 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 {
12 public:
13     int countNodes(TreeNode* root)  
14     {
15         TreeNode* l = root;
16         TreeNode* r = root;
17         // 记录左、右子树的高度
18         int hl = 0, hr = 0;
19         while (l != NULL) 
20         {
21             l = l->left;
22             hl ++;
23         }
24 
25         while (r != NULL) 
26         {
27             r = r->right;
28             hr ++;
29         }
30         // 如果左右子树的高度相同,则是一棵满二叉树
31         if (hl == hr) return (int)pow(2, hl) - 1;
32 
33         // 如果左右高度不同,则按照普通二叉树的逻辑计算
34         return 1 + countNodes(root->left) + countNodes(root->right);
35     }
36 };

 

 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 {
12 public:
13     int countNodes(TreeNode* root)  
14     {
15         if(!root) return 0;
16         return 1 + countNodes(root->left) + countNodes(root->right);
17     }
18 };

 

posted @ 2020-04-11 17:32  Jinxiaobo0509  阅读(150)  评论(0)    收藏  举报