【发布时间】:2015-02-09 02:45:36
【问题描述】:
REFERENCE 我正在复制粘贴问题和在 C 中有效的解决方案,但我无法在 Java 中使用它。我的理解主要是因为在 Java 中参数是按值传递的,这导致维护“old_value”状态的问题。但我什至尝试使用 set 和 get 将其更改为自定义 MyInt,但仍然无法使其正常工作。所以,可能我在这里也遗漏了其他东西。请建议。
给定一个二叉树,其中每个节点都有正值和负值。 将此转换为一棵树,其中每个节点都包含左侧的总和 和原始树中的右子树。叶节点的值为 改为 0。
例如下面的树
10
/ \
-2 6
/ \ / \
8 -4 7 5
应该改为
20(4-2+12+6)
/ \
4(8-4) 12(7+5)
/ \ / \
0 0 0 0
代码:
int toSumTree(struct node *node)
{
// Base case
if(node == NULL)
return 0;
// Store the old value
int old_val = node->data;
// Recursively call for left and right subtrees and store the sum as
// new value of this node
node->data = toSumTree(node->left) + toSumTree(node->right);
// Return the sum of values of nodes in left and right subtrees and
// old_value of this node
return node->data + old_val;
}
Java 代码:
public static int sumTree(Node node){
if(node == null)
return 0;
MyInt old_value = new MyInt(node.data);
node.data = sumTree(node.left) + sumTree(node.right);
return node.data + old_value.getData();
}
【问题讨论】:
-
由于您没有发布您的 Java 代码 - 很难找到您的错误...
-
只要用
int,东西都是按值复制的。 OTOHInteger是不可变的,因此通过值或引用传递它并不重要。如果您粘贴了 Java 代码,我们将有更好的机会查看其中的问题。 -
您的 C 代码无论如何都只是按值传递事物(特别是按值传递指针),所以我看不出 Java 的这方面会如何破坏任何东西。
-
啊..我完全错过了。那么当前代码应该像在 Java 中一样工作吗?那我一定是在做傻事。
标签: java algorithm binary-tree