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);
}
}
In main method:
bst.printAllRootToLeafPaths(root, new ArrayList());
But its giving wrong output.
given tree:
5
/
/
1 8
/
/
3 6 9
Expected output:
[5, 1, 3]
[5, 8, 6]
[5, 8, 9]
But the output produced:
[5, 1, 3]
[5, 1, 3, 8, 6]
[5, 1, 3, 8, 6, 9]
Can some one figure it out...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…