我正在尝试使用java在二叉树中打印所有根到叶子路径。
i am trying to print all root to leaf paths in a binary tree using java.
public void printAllRootToLeafPaths(Node node,ArrayList path) { if(node==null) { return; } path.add(node.data); if(node.left==null && node.right==null) { System.out.println(path); return; } else { printAllRootToLeafPaths(node.left,path); printAllRootToLeafPaths(node.right,path); } }主要方法:
bst.printAllRootToLeafPaths(root, new ArrayList());但它输出错误。
给定树:
5 / \ / \ 1 8 \ /\ \ / \ 3 6 9预期产出:
[5,1,3]
[5,8,6]
[5,8,9]
但产出的结果是:
[5,1,3]
[5,1,3, 8,6,
[5, 1, 3, 8, 6]
[5,1,3,8,6,9]
[5, 1, 3, 8, 6, 9]
可以算出来......
Can some one figure it out...
推荐答案用以下方法调用递归方法:
Call the recursive methods with:
printAllRootToLeafPaths(node.left, new ArrayList(path)); printAllRootToLeafPaths(node.right, new ArrayList(path));当你传递路径时会发生什么 (而不是 new ArrayList(path)是你在所有方法调用中使用单个对象,这意味着当你返回原始调用者时,该对象不在与原来相同的状态。
What happens there when you pass the path (instead of new ArrayList(path) is that you use a single object in all methods call, which means that, when you return to the original caller, the object is not in the same state as it was.
您只需要创建一个新对象并将其初始化为原始值。这样原始对象就不会被修改。
You just need to create a new object and initialize it to the original values. This way the original object does not get modified.
更多推荐
在二叉树中打印所有根到叶子路径
发布评论