Leetcode 222. Count Complete Tre
2018-08-30 本文已影响5人
SnailTyan
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Count Complete Tree Nodes2. Solution
/**
* 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);
}
}
};