1

I know how to find the size of a tree with recursion, but I am unsure on how to find it without recursion. Here is what i have so far. I think that it is my if statement that is preventing me from transversing the tree.

  public int size() {
    size = 0;
    NodeWord current = root;
    while(current != null) {
        if(current.left != null) {
            size++;
        }
        else {
            current = current.right;
        }
    }
    return size;
}
Vmax20
  • 27
  • 5

1 Answers1

1

Whenever you wish to transform a recursive solution to an iterative one, you can use a Stack.

  • In this case you can use a Stack<Node>, where Node is a Node of the binary search tree.

  • You start by pushing the root Node into the Stack.

  • Then you write a while loop that keeps going until the Stack is empty.

  • In each iteration of the while loop you can peek at the top Node of the Stack and push the children of that Node into the Stack. If it has no children, you pop that Node out of the Stack and do whatever calculation you need to do with it (just increment a counter in your example).

  • You can change the order in which you push and pop the current Node and its two children depending on the desired order of traversal of the tree.
Eran
  • 387,369
  • 54
  • 702
  • 768
  • That was really helpful thanks. I had one follow up question regarding Binary Search Trees. What is meant by a Level in a BST. Does one level describe a branch or and entire subtree? – Vmax20 Nov 08 '17 at 22:25