果然java不适合做acm。我看到上面一个人的答案写的代码,只是我把他的c++写成了java。于是碰到一个大的数组就超时了。。我确定我的代码和他的代码是一样的。所以只能直接贴代码了,有人都开始用java调用c++来执行了。也不行看来真的是java的速度问题。
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public int countNodes(TreeNode root) {
if(root==null)
{
return 0;
}
int result=1;
int nLeft=deep(root.left);
int nRight=deep(root.right);
if(nLeft==nRight)
{
result+=Math.pow(2, nLeft)-1;
result+=countNodes(root.right);
}
else
{
result+=Math.pow(2, nRight)-1;
result+=countNodes(root.left);
}
return result;
}
public int deep(TreeNode root)
{
if(root==null)
{
return 0;
}
int n=1;
while(root.left!=null)
{
n++;
root=root.left;
}
return n;
}
}
c++版代码
public class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
int l = getLeftCount(root.left);
int r = getLeftCount(root.right);
if(l==r){
return (int)Math.pow(2,l)+countNodes(root.right);
}else{
return (int)Math.pow(2,r)+countNodes(root.left);
}
}
public int getLeftCount(TreeNode n){
int count = 0;
while(n!=null){
n = n.left;
count++;
}
return count;
}
本文探讨了使用Java进行ACM编程时遇到的问题,通过对比C++和Java实现,揭示了Java在处理大型数组时的性能瓶颈,并提供了一种优化策略。详细分析了一个用于计算二叉树节点数目的Java代码实例,展示了如何调整算法以提高效率。
1117

被折叠的 条评论
为什么被折叠?



