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.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
return bs(root, 1, mostLeftLevel(root, 1));
}
private int bs(TreeNode root, int level, int h) {
// TODO Auto-generated method stub
if (level == h) {
return 1;
}
if (mostLeftLevel(root.right, level+1) == h) {
return (1 << (h - level)) + bs(root.right, level+1, h);
} else {
return (1 << (h - level - 1)) + bs(root.left, level+1, h);
}
}
private int mostLeftLevel(TreeNode root, int i) {
// TODO Auto-generated method stub
while (root != null) {
i++;
root = root.left;
}
return i - 1;
}
}
本文介绍了一种计算完全二叉树中节点数量的方法。通过递归地确定树的高度和最左侧节点的位置来实现高效的计数。文章提供了一个具体的Java实现示例。
1116

被折叠的 条评论
为什么被折叠?



