这个题目最开始算2的次方用了Math.pow,发现超时,改用1<<left之后通过。看来pow的开销是很大的啊
public class Solution { public int countNodes(TreeNode root) { return helper(root); } public int helper(TreeNode root) { if (root == null) { return 0; } int left = 0; int right = 0; TreeNode p = root; while (p != null) { left ++; p = p.left; } p = root; while (p != null) { right ++; p = p.right; } if (left == right) { return (1 << left) - 1; } else { return helper(root.left) + helper(root.right) + 1; } } }