Count Complete Tree Nodes
完全二叉树的节点数
思路:这道题使用暴力法为O(n)会超时。使用二分的思想,首先求出左右子树的深度,如果它们的深度相同,则说明左子树为满树,它的节点数可由公式2^h-1求得;如果不相同,说明右子树为满树,同样可用公式求得它的节点数。然后再递归的去求另一个子树。时间复杂度为O(lgn * lgn)。
这道题的一个优化方法是:每次递归函数都要求2^h,如果调用Math.pow(2, h)会很慢,因此用1<<h来求2^h就能AC了。
public class Solution { public int countNodes(TreeNode root) { if (root == null) { return 0; } int left_h = 0; int right_h = 0; TreeNode cur = root.left; while (cur != null) { cur = cur.left; left_h++; } cur = root.right; while (cur != null) { cur = cur.left; right_h++; } if (left_h != right_h) { return (1 << right_h) + countNodes(root.left); } else { return (1 << left_h) + countNodes(root.right); } } }