您的位置:首页 > Web前端 > Node.js

[LeetCode]Count Complete Tree Nodes

2015-11-30 12:39 561 查看
这个题目最开始算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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: