# LeetCode Count Complete Tree Nodes

172人阅读 评论(0)

Description:

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.

Solution:

import java.util.*;

public class Solution {

public int countNodes(TreeNode root) {
if (root == null)
return 0;

int leftH = getLeftHeight(root);
int rightH = getRightHeight(root);

if (leftH == rightH) {
return (1 << leftH) - 1;
} else {

return countNodes(root.left) + countNodes(root.right) + 1;
}
}

int getLeftHeight(TreeNode root) {
TreeNode temp = root;
int len = 0;
while (temp != null) {
temp = temp.left;
len++;
}
return len;
}

int getRightHeight(TreeNode root) {
TreeNode temp = root;
int len = 0;
while (temp != null) {
temp = temp.right;
len++;
}
return len;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：61630次
• 积分：3254
• 等级：
• 排名：第10408名
• 原创：288篇
• 转载：0篇
• 译文：0篇
• 评论：4条
文章分类
阅读排行
最新评论