LeetCode222——Count Complete Tree Nodes

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 2hnodes inclusive at the last level h.

实现:
class Solution {
public:
    int getHeight(TreeNode* root) {
        int h = 0;
        while (root) {
            root = root->left;
            h++;
        }
        return h;
    }
    int countNodes(TreeNode* root) {
        if (!root) return 0;
        int lh = getHeight(root->left);
        int rh = getHeight(root->right);
        
        if (lh == rh) 
            return pow(2, lh) + countNodes(root->right);
        return pow(2, rh) + countNodes(root->left);
    }
};























以上是关于LeetCode222——Count Complete Tree Nodes的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode222——Count Complete Tree Nodes

Leetcode 222. Count Complete Tree Nodes

LeetCode OJ 222. Count Complete Tree Nodes

[LeetCode] 222. Count Complete Tree Nodes Java

[Leetcode] Binary search -- 222. Count Complete Tree Nodes

leetcode 222.Count Complete Tree Nodes