[leetcode 222]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.
完全ツリーのすべてのノードの個数を計算します.
暴力タイムアウトは、まずその木が完全な二叉樹であるかどうかを判断し、そうであれば性質を解き、そうでなければ暴力を解く.
ACコード:
class Solution {
public:
    int countNodes(TreeNode* root) {
    if(root==NULL)
        return 0;
    int l=1;
    int r=1;
    TreeNode *tempLeft=root;
    TreeNode *tempRight=root;
    while(tempLeft)
    {
        tempLeft=tempLeft->left;
        ++l;
    }
    while(tempRight)
    {
        tempRight=tempRight->right;
        ++r;
    }
    if(l==r)
        return 1<<l-1;
    else
        return countNodes(root->left)+countNodes(root->right)+1;
    }
};
  Leetcode  AC  :https://github.com/PoughER/leetcode