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)
You can do the following,
public static void printTreePaths(Node node) {
int treeHeight = treeHeight(node);
int[] path = new int[treeHeight];
printTreePathsRec(node, path, 0);
}
private static void printTreePathsRec(Node node, int[] path, int pathSize) {
if (node == null) {
return;
}
path[pathSize++] = node.data;
if (node.left == null & node.right == null) {
for (int j = 0; j < pathSize; j++ ) {
System.out.print(path[j] + " ");
}
System.out.println();
}
printTreePathsRec(node.left, path, pathSize);
printTreePathsRec(node.right, path, pathSize);
}
public static int treeHeight(Node root) {
if (root == null) {
return 0;
}
if (root.left != null) {
treeHeight(root.left);
}
if (root.right != null) {
treeHeight(root.right);
}
return Math.max(treeHeight(root.left), treeHeight(root.right)) + 1;
}