题目链接:https://leetcode.com/problems/count-complete-tree-nodes/
题目:
complete
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.
思路:
满二叉树每层结点数目是2^(h-1),共2^h-1。利用上述定理,递归求结点个数。还有求2^h-1用移位不会超时,用math.pow会超时。
算法:
public int countNodes(TreeNode root) {
if (root == null)
return 0;
//求root左右高度
TreeNode tmp = root.left;
int leftHeight = 1;
while (tmp != null) {
tmp = tmp.left;
leftHeight++;
}
tmp = root.right;
int rightHeight = 1;
while (tmp != null) {
tmp = tmp.right;
rightHeight++;
}
//====end
if (leftHeight == rightHeight)
return (2 << (leftHeight - 1)) - 1; //如果用Math.pow计算会超时,so why?
return 1 + countNodes(root.left) + countNodes(root.right);
}