在Java中将二叉树转换为求和树

时间:2015-02-08 04:27:22

标签: java algorithm binary-tree

REFERENCE我正在复制粘贴问题以及在C中工作的解决方案,我无法在Java中使用它。我理解主要是因为在Java中参数是按值传递的,这导致问题维持“old_value”的状态。但我甚至尝试将它更改为自定义MyInt with set和get,仍然无法使其正常工作。所以,我可能也错过了其他的东西。请建议。

  

给定二叉树,其中每个节点具有正值和负值。   将其转换为树,其中每个节点包含左侧的总和   和原始树中的右子树。叶节点的值是   改为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();
    }

1 个答案:

答案 0 :(得分:3)

我的测试运行错误。相同的代码逻辑将在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;
    }