LeetCode222 Count CompleteTree Nodes(计算完全二叉树的节点数) Java 题解

1010人阅读 评论(0)

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.

public static int countNodes(TreeNode root) {
if(root==null)
return 0;
else {
int left=getLeftHeight(root);
int right=getRightHeight(root);
if(left==right)
return (1<<left)-1;
else {
return countNodes(root.right)+countNodes(root.left)+1;
}
}
}

public static int  getRightHeight(TreeNode root) {
int height=0;
while(root!=null)
{
height++;
root=root.left;
}
return height;

}

public static int  getLeftHeight(TreeNode root) {
int height=0;
while(root!=null)
{
height++;
root=root.right;
}
return height;

}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：35294次
• 积分：896
• 等级：
• 排名：千里之外
• 原创：56篇
• 转载：1篇
• 译文：0篇
• 评论：13条
文章分类
最新评论