Leetcode 222: Count Complete Tree Nodes

Do only the recursion will cause TLE. Thus, at each node, count the heights of its left subtree and right subtree, if left height equals to the right height, the number of nodes of this root can be calculated in the mathematical way.

/**
 * 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 hl=0,hr=0;
        TreeNode *l=root->left,*r=root->right;
        while(l)
        {
            l=l->left;
            hl++;
        }
        while(r)
        {
            r=r->right;
            hr++;
        }
        if(hl==hr)
            return (1<<hl+1)-1;//equals to pow(2,hl+1)-1,increase the speed
        return 1+countNodes(root->left)+countNodes(root->right);
    }
};


發佈了186 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章