leetcode面试准备:Count Complete Tree Nodes
1 题目
Given a complete binary tree, count the number of nodes.
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.
接口:public int countNodes(TreeNode root);
2 思路
思路1
用暴力法:不考虑完全二叉树的特性,直接遍历求节点数。---超时
复杂度: Time:O(N); Space:O(log N)
思路2
完全二叉树的节点数,可以用公式算出 2^h - 1
. 如果高度不相等, 则递归调用 countNodes(root.left) + 1 + countNodes(root.right)
复杂度: Time:O(log N); Space:O(log N)
思路3
二分查找的思想,感觉和思路2差不多。但是代码写出来的效率高一些。
复杂度: Time:O(log N); Space:O(1)
3 代码
思路1
public int countNodes0(TreeNode root) {
if (root == null)
return 0;
return countNodes(root.left) + 1 + countNodes(root.right);
}
思路2
public int countNodes(TreeNode root) {
if (root == null)
return 0;
int leftHigh = 0, rightHigh = 0;
TreeNode lchild = root.left, rchild = root.right;
for (; lchild != null;) {
leftHigh++;
lchild = lchild.left;
}
for (; rchild != null;) {
rightHigh++;
rchild = rchild.right;
}
if (leftHigh == rightHigh) {
return (2 << leftHigh) - 1;
} else {
return countNodes(root.left) + 1 + countNodes(root.right);
}
}
4 总结
计算阶乘的注意: (2 << leftHigh) - 1
才不会超时,用Math.pow()
超时。
二分查找思想,自己很不熟练。多找题目联系联系。
5 参考
posted on 2015-08-04 22:05 BYRHuangQiang 阅读(265) 评论(0) 编辑 收藏 举报