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

LeetCode222——Count Complete Tree Nodes

时间:2015-08-13 01:13:54      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   二叉树   完全二叉树   

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 2hnodes inclusive at the last level h.

实现:
class Solution {
public:
    int getHeight(TreeNode* root) {
        int h = 0;
        while (root) {
            root = root->left;
            h++;
        }
        return h;
    }
    int countNodes(TreeNode* root) {
        if (!root) return 0;
        int lh = getHeight(root->left);
        int rh = getHeight(root->right);
        
        if (lh == rh) 
            return pow(2, lh) + countNodes(root->right);
        return pow(2, rh) + countNodes(root->left);
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode222——Count Complete Tree Nodes

标签:leetcode   c++   二叉树   完全二叉树   

原文地址:http://blog.csdn.net/booirror/article/details/47460605

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