forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 222.Count-Complete-Tree-Nodes_v1.cpp
- Loading branch information
1 parent
dfde758
commit cda371b
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
55 changes: 55 additions & 0 deletions
55
Tree/222.Count-Complete-Tree-Nodes/222.Count-Complete-Tree-Nodes_v1.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
/** | ||
* 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==NULL) return 0; | ||
|
||
int ret = 1; | ||
int h1 = findLeftDepth(root->left); | ||
int h2 = findRightDepth(root->left); | ||
int h3 = findLeftDepth(root->right); | ||
int h4 = findRightDepth(root->right); | ||
|
||
if (h1==h2) | ||
{ | ||
ret += pow(2,h1)-1; | ||
return ret+countNodes(root->right); | ||
} | ||
else | ||
{ | ||
ret += pow(2,h3)-1; | ||
return ret+countNodes(root->left); | ||
} | ||
} | ||
|
||
int findLeftDepth(TreeNode* node) | ||
{ | ||
int count = 0; | ||
while (node!=NULL) | ||
{ | ||
count++; | ||
node=node->left; | ||
} | ||
return count; | ||
} | ||
|
||
int findRightDepth(TreeNode* node) | ||
{ | ||
int count = 0; | ||
while (node!=NULL) | ||
{ | ||
count++; | ||
node=node->right; | ||
} | ||
return count; | ||
} | ||
}; |