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)
Here is my solution: Once we traverse the left or right path just remove the last element.
Code:
public static void printPath(TreeNode root, ArrayList list) {
if(root==null)
return;
list.add(root.data);
if(root.left==null && root.right==null) {
System.out.println(list);
return;
}
else {
printPath(root.left,list);
list.remove(list.size()-1);
printPath(root.right,list);
list.remove(list.size()-1);
}
}