Title:
given a complete binary tree, obtains the number of nodes of the tree.
Description:
Complete binary tree is defined as follows: in the binary tree, except the bottom node may not be filled, the remaining maximum number of nodes each, and the bottom layer of nodes are concentrated in a plurality of layers of the leftmost position. If the bottom of the h layer, the layer comprising the nodes 1 ~ 2h.
Example:
Input:
Output: 6
/**
- There are two possibilities:
- 1, hl = hr left subtree full, direct calculation of the left subtree and recursively right subtree
- 2, hl> hr right subtree of the full tree, than the left subtree low level, direct calculation of the right subtree node, then the left subtree recursively
- The time complexity of O (h ^ 2) h is the height of the tree
* /
public int countNodes(TreeNode root) {
if (root == null)
return 0;
int hl = depth(root.left);
int hr = depth(root.right);
if (hl == hr) {
// 注:1 为根节点 (1 << hl) - 1 为左子树节点个数 countNodes(root.right)为右子树节点个数
return 1 + ((1 << hl) - 1) + countNodes(root.right);
} else {
return 1 + ((1 << hr) - 1) + countNodes(root.left);
}
}
private int depth(TreeNode node) {
int d = 0;
while (node != null) {
node = node.left;
d++;
}
return d;
}