leetcode 222.Count Complete Tree Nodes

Posted newnoobbird

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 222.Count Complete Tree Nodes相关的知识,希望对你有一定的参考价值。

完全二叉树是从左边开始一点点填充节点的,因此需要计算所有的节点的个数。

则分别从左边和右边来进行传递的,当左右是完全二叉树的时候,其节点个数就是pow(2,h)-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) {
        int hleft=0, hright=0;
        TreeNode* pleft=root, *pright=root;
        while(pleft){
            hleft++;
            pleft=pleft->left;
        }
        while(pright){
            hright++;
            pright=pright->right;
        }
        if(hleft==hright) return pow(2,hleft)-1;
        return countNodes(root->left)+countNodes(root->right)+1;
    }
};

 

以上是关于leetcode 222.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