【发布时间】:2013-09-17 15:46:01
【问题描述】:
这是我编写的用于打印二叉树从根到叶的所有路径的代码:
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,但我无法遵循该答案。谢谢。
【问题讨论】:
-
每次调用
printRootToLeaf时,都会向list添加一个节点。因此,每次打印list时,它的大小都会增加也就不足为奇了。
标签: java algorithm binary-tree tree-traversal