I have trying print all paths from in a binary tree. I am able to print all paths in the tree. but the problem is its not printing some redundant zeros in the output. Does arrays get initialized with zeros ? if yes then how to overcome the problem in the case like this ? I am learning and thats why I have posted this question here to learn more and overcome errors.
public class PrintAllPath {
static void printAllPaths(Tree tree) {
int[] paths = new int[1000];
printPathsRecur(tree, paths, 0);
}
static void printPathsRecur(Tree tree, int paths[], int pathlen) {
if (tree == null)
return;
paths[pathlen++] = tree.val;
pathlen++;
if (tree.left == null && tree.right == null) {
printArray(paths, pathlen);
} else {
printPathsRecur(tree.left, paths, pathlen);
printPathsRecur(tree.right, paths, pathlen);
}
}
static void printArray(int paths[], int pathlen) {
for (int i = 0; i < pathlen; i++) {
System.out.println("Node : " + paths[i]);
}
}
static Tree insert(Tree tree, int element) {
Tree tree2 = new Tree(element, null, null);
if (tree == null)
tree = tree2;
else if (element < tree.val)
tree.left = insert(tree.left, element);
else
tree.right = insert(tree.right, element);
return tree;
}
static void print(Tree tree) {
if (tree == null)
return;
System.out.println(tree.val);
print(tree.left);
print(tree.right);
}
public static void main(String[] args) {
Tree tree = new Tree(new Integer(5), null, null);
tree = insert(tree, 10);
tree = insert(tree, 100);
tree = insert(tree, 11);
tree = insert(tree, 110);
tree = insert(tree, 50);
System.out.println("The tree is as follows : ");
print(tree);
printAllPaths(tree);
}
}
Ouput :
The tree is as follows :
5
10
100
11
50
110
5 0 10 0 100 0 11 0 50 0 5 0 10 0 100 0 110 0
Yes, in Java,
new int[X]creates a zero-initialized array.From JLS §4.12.5:
Anyway, the reason you’re getting zeros is because you increment
pathlentwice every time you insert an element, so you insert an element and then skip the next element (leaving it at 0):You only have to increment once.