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)
We can use recursion to achieve it. Right data structure makes it concise and efficient.
List> printPath(Tree root){
if(root==null)return null;
List> leftPath= printPath(root.left);
List> rightPath= printPath(root.right);
for(LinkedList t: leftPath){
t.addFirst(root);
}
for(LinkedList t: rightPath){
t.addFirst(root);
}
leftPath.addAll(rightPath);
return leftPath;
}