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 2h nodes inclusive at the last level h.
完全二叉樹:除了最後一層,第i+1層都有2^i個節點,最後一層可能缺失從右邊開始連續的
幾個節點

等比數列求和公式:
Sn = a(1-q^n)/(1-q) 
2^0 + 2^1 + 2^2+ ...+2^(n-1)=2^n -1

尋找最後一層從右邊數第一個不爲空的節點,採用二分法查找,通過本節點的層數h(同過一直計算
左支點的個數)與右節點的層數h2比較來把樹分成兩個子樹,如果h==h2-1則說明左子樹爲滿二叉樹,
則轉向右子樹計算......
*/

/**
 * 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) {//Time linit exceeded
        if(!root) return 0;
        return countNodes(root->left)+countNodes(root->right)+1;
    }
    int height(TreeNode* root){
        int i=0;
        while(root){
            root=root->left;
            i++;
        }
        return i;
    }
    int countNodes(TreeNode* root) {
        int h=height(root);
        return h==0 ? 0 : height(root->right)==h-1 ? (1<<h-1) + countNodes(root->right) : (1<<h-2) + countNodes(root->left);
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章