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

标签 java algorithm binary-tree tree-traversal

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

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);

}

我在 main 中调用这个方法是这样的:

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]

我应该修复什么才能使这项工作正常进行?我知道这类似于 this ,但我无法遵循该答案。谢谢。

最佳答案

问题是您没有删除元素,所以您沿着树的一侧向下移动,填满列表,然后向下移动另一侧,旧元素仍然存在。

删除元素的未经测试的代码:

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);
        // cast so we don't remove by index (would happen if 'data' is an int)
        list.remove((Integer)root.data);
        return;
    }

    printRootToLeaf(root.left, list);
    printRootToLeaf(root.right, list);
    // cast so we don't remove by index  (would happen if 'data' is an int)
    list.remove((Integer)root.data);
}

remove(Object) 不是特别有效,使用 LinkedList 然后使用 removeLast() 可能是个好主意。

关于java - 打印二叉树中从根到叶的所有路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18854264/

相关文章:

algorithm - AVL树中诱导的高度不平衡

java - 如何测试(模拟)使用外部 API 的对象(Jama Software)

java - 保证消息异步传送

java - 我的数据与用户输入和数据库不一样

ruby - 快速排序实现 : stack level too deep (SystemStackError)

performance - 随机设置位的最佳位图压缩

c++ - 求解 D 给定 A、B、C 和 C-D 的长度,平行于 A-B

algorithm - 使用具有重复值的中序和预序构造二叉树

c - C中二叉搜索树的删除

java - 公开 JSP 文件中未使用的属性 (Spring)