0

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?

April_Nara
  • 1,024
  • 2
  • 15
  • 39

1 Answers1

0

It...should return t = [1,2,4,3,5] and I am getting [].

Well, let's look at the for-loop you're using to populate your Queue:

for (Tree<Integer> node = root; node != null; node = queue.poll()) {
    //stuff
}

What you're doing here is looping until queue.poll() returns null, and if we look at the javadoc for ArrayDeque, we see that poll()

Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.

So, basically you are looping until your Queue is empty, then creating an array based on its size to return. Since its size is always zero, you always return a zero-length array.

It looks like you're looking to do a Preorder traversal, so what you need to do is to rewrite your method using a proper algorithm.

If you're committed to a non-recursive traversal, here's an algorithm for doing it that way, instead.

azurefrog
  • 10,785
  • 7
  • 42
  • 56