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

【LeetCode】222. Count Complete Tree Nodes

时间:2015-07-09 19:33:00      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

完全二叉树相比普通二叉树,在计数时候一个trick在于,当最后一层是满的(最左深度等于最右深度),

就不需要通过遍历方式来计数,直接等于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) {
        if(root == NULL)
            return 0;
        TreeNode* l = root;
        int lefth = 0;
        while(l->left)
        {
            lefth ++;
            l = l->left;
        }
        TreeNode* r = root;
        int righth = 0;
        while(r->right)
        {
            righth ++;
            r = r->right;
        }
        if(lefth == righth)
            return pow(2.0, lefth+1) - 1;
        else
            return 1 + countNodes(root->left) + countNodes(root->right);
    }
};

技术分享

 

【LeetCode】222. Count Complete Tree Nodes

标签:

原文地址:http://www.cnblogs.com/ganganloveu/p/4633843.html

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