设为首页 加入收藏

TOP

LeetCode222――Count Complete Tree Nodes
2015-11-21 00:55:22 来源: 作者: 【 】 浏览:1
Tags:LeetCode222 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 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);
}
};

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 3746 Cyclic Nacklace KMP循.. 下一篇C++ 程序设计基本概念 知识点 小结

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: