Count Complete Tree Nodes - LeetCode 222

題目描述:
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

分析:
由於是二叉搜索樹,那麼就滿足完全二叉樹的結構。只有可能最後一層的右邊會少幾個結點。
因此,如果是滿二叉樹的話,只需要求出整顆二叉搜索樹的層數h,然後利用滿二叉樹的性質:節點數爲2^h-1。
否則就只有分別求出左子樹的結點數與右子樹的結點數之和了。求這兩個字數的結點數的方法和判斷根節點一樣,也是先判斷是否是滿二叉樹,即遞歸調用即可。

以下是C++實習代碼:

/**//////////////////////84ms*/
/**
 * 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 lef_height(TreeNode* root){ //求出左子樹的最大層次
        int cnt = 0;
        while(root != NULL){
            cnt++;
            root = root->left;
        }
        return cnt;    
    }
    int rig_height(TreeNode* root){ //求出右子樹的最大層次
        int cnt = 0;
        while(root != NULL){
            cnt++;
            root = root->right;
        }
        return cnt;    
    }
    
    int countNodes(TreeNode* root) {
        int cnt = 0;
        if(root == NULL)
            return cnt;
        int lef = lef_height(root);
        int rig = rig_height(root);
        if(lef == rig) //左右子樹的層次是相等的,說明是滿二叉樹,直接用公式計算節點總數
            return (1<<lef)-1;
        else //不是滿二叉數,那麼遞歸調用計算出左右字數的結點數再加上根節點數即可
            return countNodes(root->left) + countNodes(root->right) + 1;
    }
};

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