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 int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = 0;
int rightHeight = 0;
// 计算leftHeight
TreeNode p = root;
while (p != null) {
p = p.left;
leftHeight++;
}
// 计算rightHeight
p = root;
while (p != null) {
p = p.right;
rightHeight++;
}
// 如果相等,满足2^n-1
if (leftHeight == rightHeight) {
return (1 << leftHeight) - 1;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。