222. Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.

计算完全二叉树的节点数目。满二叉树的节点数是2^h-1, h为树的高度。

/**
 * 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 count = 1;
       count += countNodes(root->left);
       count += countNodes(root->right);
       return count;
       -------------------*/
       if(root==NULL) return 0;
       int leftH = getLeftHeight(root);
       int rightH = getRightHeight(root);
       if(leftH==rightH)
        return (1<<leftH)-1;
       else
       {
         return countNodes(root->left) + countNodes(root->right)+1;   
       }
    }
    int getLeftHeight(TreeNode* root)
    {
        if(root==NULL) return 0;
        int h = 1;
        while(root->left)
        {
            h++;
            root= root->left;
        }
        return h;
    }
    int getRightHeight(TreeNode* root)
    {
        if(root==NULL) return 0;
        int h = 1;
        while(root->right)
        {
            h++;
            root= root->right;
        }
        return h;
    }
};


你可能感兴趣的:(222. Count Complete Tree Nodes)