我试图使用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、9]
可以找出一个…