这是我编写的用于打印二叉树从根到叶的所有路径的代码:
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]
我应该解决什么问题才能完成这项工作?我知道这与此类似,但我无法遵循该答案。谢谢。