小编典典

在二叉树中打印从根到叶的所有路径

algorithm

这是我编写的从根到叶打印二叉树的所有路径的代码:

public static void printRootToLeaf(Node1 root, List<Integer> list) {
    if(root == null) {
        return;
    }

    list.add(root.data);

    if(root.left == null && root.right == null) {
        System.out.println(list);
        return;
    }

        printRootToLeaf(root.left, list);
        printRootToLeaf(root.right, list);

}

我主要这样调用此方法:

public static void main(String[] args) {

    Node1 root = new Node1(1);
    Node1 two = new Node1(2);
    Node1 three = new Node1(3);
    Node1 four = new Node1(4);
    Node1 five = new Node1(5);
    Node1 six = new Node1(6);
    Node1 seven = new Node1(7);
    Node1 eight = new Node1(8);

    root.left = two;
    root.right = three;
    two.left = four;
    two.right = five;
    three.left = six;
    three.right = seven;
    five.left = eight;

    printRootToLeaf(root, new ArrayList<Integer>());

}

我得到结果:

[1, 2, 4]
[1, 2, 4, 5, 8]
[1, 2, 4, 5, 8, 3, 6]
[1, 2, 4, 5, 8, 3, 6, 7]

当我期待的时候:

[1, 2, 4]
[1, 2, 5, 8]
[1, 3, 6]
[1, 3, 7]

我应该解决什么才能使其正常工作?我知道这是类似这样的,但我无法遵循答案。谢谢。


阅读 290

收藏
2020-07-28

共1个答案

小编典典

这是一个简单的例子。

Node1 root = new Node1(1);
root.left = new Node(2);
root.right = new Node(3);

与预期的结果

[1,2]
[1,3]

和实际结果

[1,2]
[1,2,3]

首次调用printRootToLeaf时List为空。您添加1,并printRootToLeaf在左侧分支上调用。在该调用中,将2添加到列表中,然后打印[1,2]。然后,您返回第一个电话,但
清单2仍在! 然后printRootToLeaf,您在右边的分支上调用。在该调用中,将3加到列表中,然后打印[1,2,3]

递归到左分支时对列表所做的更改不应传播到右分支下传递的列表。解决此问题的最简单方法是每次都复制列表:

printRootToLeaf(root.left, copy(list));
printRootToLeaf(root.right, copy(list));

复制列表的实际方法将根据您使用的语言而有所不同。

2020-07-28