Trying to traverse a tree and getting null value for my array. I need to traverse the tree that only allows access to the right and left children with no root in the class definition for the Node class.
class Tree<T> {
Tree(T x) {
value = x;
}
T value;
Tree<T> left;
Tree<T> right;
}
public int[] traverseTree(Tree<Integer> t) {
Stack<Tree<Integer>> stack = new Stack<Tree<Integer>>();
Tree<Integer> node = root;
while (node != null) {
stack.push(node);
node = node.left;
}
int[] result = new int[stack.size()];
int i = 0;
while (stack.size() > 0) {
node = stack.pop();
if(node != null) {
result[i] = node.value;
i++;
}
if (node.right != null) {
node = node.right;
while (node != null) {
stack.push(node);
node = node.left;
}
}
}
return result;
}
It takes an input of
t = {
"value": 1,
"left": {
"value": 2,
"left": null,
"right": {
"value": 3,
"left": null,
"right": null
}
},
"right": {
"value": 4,
"left": {
"value": 5,
"left": null,
"right": null
},
"right": null
}
}
This should return [1,2,4,3,5] and I am getting []. I've also tried looping like
if(root != null) {
queue.add(root);
}
while(root.left != null) {
while(root.right != null) {
queue.add(root);
root = root.right;
}
queue.add(root);
root = root.left;
}
This also doesn't work. This too will give me back a [] array. The traversal should print the tree from left to right on the tree level indicated by the tree height (which is the level). Any thoughts?