Leetcode 222. Count Complete Tree Nodes

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Count Complete Tree Nodes

2. Solution

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

Reference

  1. https://leetcode.com/problems/count-complete-tree-nodes/description/
如果有收获,可以请我喝杯咖啡!