0

I have a B-Tree that I can currently iterate over using recursive inorder traversal. However, I need to iterate inorder NOT recursively. I have tried all kinds of things and the closest I got was using depth-first-search. I am successfully printing all the elements in the tree however not in the correct order. I do understand why its not in sorted order but I don't understand how I can fix it.. This is what I got:

public void iterative() {
            Stack<BTreeNode<T>> stack = new Stack<>();
            stack.push(this);
            while(!stack.empty()) {
                BTreeNode<T> curr = stack.pop();

                int i;
                for (i = 0; i < curr.numNodes; i++) {

                    if (!curr.isLeaf) {
                        stack.push(curr.children[i]);
                    }
                    System.out.println(curr.keys[i].toString());
                }
                if (!curr.isLeaf) {
                    stack.push(curr.children[i]);
                }
            }
        }
    ```

What am I missing here?
c0der
  • 18,467
  • 6
  • 33
  • 65
Luka Jozić
  • 162
  • 2
  • 12
  • Why the extra `if (!curr.isLeaf) { stack.push(curr.children[i]); }` outside the loop? – tgdavies Sep 18 '21 at 06:11
  • It doesnt iterate over all the elements without that i guess its to grab the rest. – Luka Jozić Sep 18 '21 at 06:22
  • Why do you expect DFS to perform inorder traversal ? I don't see a recursive DFS in your code. Please post [mre] including hard codes test data. – c0der Sep 18 '21 at 13:11
  • Just having nodes on the stack is not enough; you should have a stack with pairs of nodes and *indexes*, so you know how many of the children you have already processed, and which key you should output, and which remaining children need to be visited still. – trincot Sep 18 '21 at 16:37
  • @c0der Sorry if it was unclear but what I posted is my attempt at the iterative solution. But I can do this recursively with a similar algorithm I just didn't post that. – Luka Jozić Sep 19 '21 at 16:08
  • @trincot Would you mind showing me like some pseudo code or refer me to an example? Im not quite sure what you mean. – Luka Jozić Sep 19 '21 at 16:08
  • We can't help with a code we don't see – c0der Sep 19 '21 at 16:24
  • @c0der The code I posted is the code I need help with. – Luka Jozić Sep 19 '21 at 16:31
  • OK. "Please post minimal reproducible example including hard codes test data" and the expected output. – c0der Sep 19 '21 at 16:34

0 Answers0