[LeetCode222]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 2h nodes inclusive at the last level h.

Hide Tags Tree Binary Search
Hide Similar Problems (E) Closest Binary Search Tree Value

这道题费了不少时间。
首先complete binary tree 就是除了最后一层可能不满,其他层都是满的。 其次如果一个binary tree heigh 是h,则它的node一共有pow(2,h)-1。这个幂指数函数又等价于 (1<<h)。知道这几点,我们就知道总的node 数为

(1<<(height1))1+cnt
where cnt is the nodes of last level.

下面这个code最快,还需要好好理解一下,基本就是tmp找到了最后一个node的位置。。

/**
 * 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;
        TreeNode *temp = root;
        int height = 0, count = 0, level;
        while(temp) {
            temp = temp->left;
            height ++;
        }
        temp = root;
        level = height - 2;
        while(level >= 0) {
            TreeNode *left = temp->left;
            for(int i = 0;i < level;i ++) {
                left = left->right;
            }
            if(left) {//which means there might be more node in right sub part, then tmp goes rightward.
                temp = temp->right;
                count += (1 << level);
            } else temp = temp->left;
            level --;
        }
        if(temp) count ++;
        return (1 << (height - 1)) + count - 1;
    }
};

传统recursion比较好理解, 但时间复杂度较高: O(h^2).

/**
 * 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;
        TreeNode* l = root;
        TreeNode* r = root;
        int cntL = 0, cntR = 0;
        while(l){
            ++cntL;
            l = l->left;
        }
        while(r){
            ++cntR;
            r = r->right;
        }
        if(cntL == cntR) return (1 << cntL) - 1;
        else return 1 + countNodes(root->left) + countNodes(root->right);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章