Here is the code I wrote to print all paths of a Binary tree from root to leaf:
public static void printRootToLeaf(Node1 root, List list) {
The question here is how did you get the solution rather than did you get the solution. The performance is the key here. Create a tree object first..
class Node {
public Node left;
public Node right;
public Character val;
public Node(char val) {
this.val = val;
}
get all paths in list..
public List> printPath(Node root) {
if (root == null) return new ArrayList>();
List> left = printPath(root.left);
List> right = printPath(root.right);
left.addAll(right);
for (LinkedList lst : left) {
lst.addFirst(root);
}
if(left.size()==0){
LinkedList lst= new LinkedList();
lst.add(root);
left.add(lst);
}
return left;
}
print all the paths now..
Node root = new Node('a');
System.out.println(root.val);
root.left = new Node('b');
root.left.left = new Node('c');
root.left.right = new Node('d');
root.right = new Node('e');
root.right.left = new Node('f');
root.right.right = new Node('g');
root.right.right.left = new Node('h');
List> allPaths = wc.printPath(root);
for (LinkedList lst : allPaths) {
for (Node node : lst)
System.out.print(node.val==null ? "-" : node.val);
System.out.println();
}