您的位置:首页 > Web前端 > Node.js

[leetcode][tree] Count Complete Tree Nodes

2015-06-07 17:19 627 查看
题目:

Given a complete binary
tree, count the number of nodes.

/**
* 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(NULL == root) return 0;
TreeNode *p = root->left;
int leftHeight = 0, rightHeight = 0;
//求得左子树的高度
while(p != NULL){
p = p->left;
++leftHeight;
}
//求得右子树的高度
p = root->right;
while(p != NULL){
p = p->right;
++rightHeight;
}
//如果两者等高,则说明是满二叉树,直接计算得到节点个数
if(leftHeight == rightHeight){//满二叉树
return (1 << (leftHeight+1))-1;
}
//如果两者不等高,递归求得左右子树的节点个数,当前树的节点个数等于左右子树节点个数之和加1(根节点)
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: