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);
    }
};

 

posted @ 2017-03-10 21:36  Tsunami_lj  阅读(95)  评论(0编辑  收藏  举报