222. Count Complete Tree Nodes

来源:互联网 发布:美国最新数据公布 编辑:程序博客网 时间:2024/05/22 10:54
/** * 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 lh=0;        int rh=0;        TreeNode * lp=root;        TreeNode * rp=root;        while(lp){            lh++;            lp=lp->left;        }        while(rp)        {            rh++;            rp=rp->right;        }        if(lh==rh)            return pow(2,lh)-1;        else             return 1+countNodes(root->left)+countNodes(root->right);    }};
1 0