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.
給一個(gè)完整二叉樹,求節(jié)點(diǎn)數(shù)目。
最直觀的方法就是遍歷,例如用深度優(yōu)先遍歷,代碼如下:

/**
 * 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) {
        int l = 0;
        TreeNode *cur = root;
        int res = 0;
        if (root)
            dfs(root, res);
        return res;
    }
    
    void dfs(TreeNode* node, int &count)
    {
        if (node)
            count++;
        else 
            return;
        dfs(node->left, count);
        dfs(node->right, count);
    }
};

沒錯(cuò),又TLE了。想想除了最后一層,其他的都可以直接算出來,因?yàn)槭菨M的,但是最后一層的節(jié)點(diǎn)數(shù)目應(yīng)該怎么算呢?
沒有什么特別直觀的想法。
看了下答案,主要是這么一個(gè)類似的剪枝過程,就是假如是滿二叉樹就直接算,不是的話就看左右子樹的情況,遞歸。

/**
 * 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) {
        TreeNode *l = root, *r = root;
        int hl = 0, hr = 0;
        while (l) {
            hl++;
            l = l->left;
        }
        while (r) {
            hr++;
            r = r->right;
        }
        return (hl == hr) ? (pow(2, hl) - 1) : (1 + countNodes(root->left) + countNodes(root->right));
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容