【发布时间】:2015-10-16 10:23:24
【问题描述】:
我已经为这个问题写了一个解决方案:
https://leetcode.com/problems/count-complete-tree-nodes/
但我得到了 TLE。我该如何优化它?
public class Solution
{
public int countNodes(TreeNode root)
{
if(root==null)
return 0;
int left = count(root.left);
int right = count(root.right);
if(left<=right)
{
return ((int)(Math.pow(2, left)-1) + countNodes(root.right) + 1);
}
else
{
return (countNodes(root.left) + (int)(Math.pow(2, right)-1) + 1);
}
}
public static int count(TreeNode root)
{
int ctr=0;
while(root!=null)
{
ctr++;
root = root.left;
}
return ctr;
}
}
树在 OJ 中定义为:
/**
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
【问题讨论】:
-
本站用于解决开发过程中出现的错误。你的问题更适合Code Review。
-
在静态 count() 方法中,您只计算左侧的节点而不是右侧的节点。作为完整性的一部分,您可能会错过正确计数。
-
@GeraldSchneider 我不知道那个网站。我一定会在未来发布相应的内容。
-
@a3.14_Infinity 我故意这样做的。问题陈述中提到“最后一层的所有节点都尽量靠左”。因此,不会出现特定节点有右孩子但没有左孩子的情况。反过来也是可能的。
标签: java algorithm data-structures tree binary-tree