222. Count Complete Tree Nodes

Posted 为了更优秀的你,加油!

tags:

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

解题思路:如何巧妙的利用完全二叉树的性质来减少复杂度是这题的核心。一棵完全二叉树的左右两部分必有一部分是满二叉树。本题就是基于此产生了logn*logn的时间复杂度算法。

/**
 * 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) {
       if(!root)return 0;
       TreeNode *l=root,*r=root;
       int hl=0,hr=0;
       while(l){hl++;l=l->left;}
       while(r){hr++;r=r->right;}
       if(hl==hr)return (1<<hl)-1;
       return 1+countNodes(root->left)+countNodes(root->right);
    }
};

 

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

222. Count Complete Tree Nodes

222. Count Complete Tree Nodes

222.Count Complete Tree Nodes

LeetCode222——Count Complete Tree Nodes

Leetcode 222. Count Complete Tree Nodes

LeetCode OJ 222. Count Complete Tree Nodes