Question
Given a complete binary tree, count the number of nodes.
Code
/**
* 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;
int l = getLeft(root), r = getRight(root);
if (l == r) return (2 << (l - 1)) - 1;
return 1 + countNodes(root.left) + countNodes(root.right);
}
public int getLeft(TreeNode node) {
int count = 1;
while (node.left != null) {
count++;
node = node.left;
}
return count;
}
public int getRight(TreeNode node) {
int count = 1;
while (node.right != null) {
count++;
node = node.right;
}
return count;
}
}
Solution
如果从某节点一直向左的高度 = 一直向右的高度, 那么以该节点为root的子树一定是complete binary tree. 而 complete binary tree的节点数, 可以用公式算出 2^h - 1. 如果高度不相等, 则递归调用 return countNode(left) + countNode(right) + 1.
网友评论