题目:
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.
思路1:
暴力解决,遍历树的所有节点,依次统计。
会超时,题目限定了该二叉树是完全二叉树,该种思路适用于所有二叉树。
思路2:
暴力解决无法测试通过,此时需要考虑完全二叉树的特点。
完全二叉树,至少有一课子树是完美二叉树,另一课子树至少是完全二叉树。
因此可以递归的计算。
判断完美二叉树:
最内侧的叶子结点和最外侧的叶子结点是否在同一层。
代码:
public static int countNodes(TreeNode root){
if(root == null){
return 0;
} int hl = getLeft(root)+1;
int hr = getRight(root)+1; if(hl == hr){
int num = (2<<(hl-1))-1;
return num;
}else{
return countNodes(root.left)+countNodes(root.right)+1;
}
} public static int getRight(TreeNode root) {
int cou = 0;
TreeNode ptr = root;
while(ptr.right != null){
cou++;
ptr = ptr.right;
}
return cou;
} public static int getLeft(TreeNode root) {
int cou = 0;
TreeNode ptr = root;
while(ptr.left != null){
cou++;
ptr = ptr.left;
}
return cou;
}