码迷,mamicode.com
首页 > 其他好文 > 详细

222. Count Complete Tree Nodes

时间:2017-03-10 22:23:39      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:ast   possible   如何   type   http   eve   lan   let   ref   

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

标签:ast   possible   如何   type   http   eve   lan   let   ref   

原文地址:http://www.cnblogs.com/tsunami-lj/p/6533202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!