参考文献我正在复制粘贴问题和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();
}发布于 2015-02-08 18:45:36
我做错测试了。同样的代码逻辑将在Java中工作,并在通过值传递的注释中正确地指出,这并没有什么区别,因为值正在被返回。以下是正在工作的Java代码:
public static int sumTree(TreeNode node){
if(node == null)
return 0;
int old_value = node.value;
node.value = sumTree(node.left) + sumTree(node.right);
return node.value + old_value;
}https://stackoverflow.com/questions/28390563
复制相似问题