Hi I am trying to print a binary search tree using a while loop and a stack. While I know that this is easier to do using recursion, for the sake of it I would prefer to do it this way and I keep running into either an infinite loop or seg fault. Can anyone here please tell me how to do this? Thanks in advance!

Hi,

So far i remember using perOrder you wont be able to sort, you need inorder traversal, but I have done long , literally long time ago.

But anyway, here is the sudo code of preorder using stack.

BSTPreOrder(Node *root){

Push root into stack.

while(stack not empty){
         node = pop stack.
         print node;

         if (node right child is not null)  // Think why we want to push right child first
             push right child.
         if ( node left child is not null)
             push left child.
}

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.