/********************PREORDER***************** 1. Create a stack and Push NULL as the first element in stack. 2. Initialize a pointer ptr = root to traverse in the tree. 3. Repeat steps 4 to 5. 4. If ptr is not NULL then a. Process Node ptr. b. push ptr to stack and set ptr = leftChild(ptr). 5. Else a. Pop top element from stack and assign it to ptr. b. If NULL is popped then return c. If ptr has right child then set ptr to rightChild(ptr) d. Else set ptr = NULL. COMPLEXITY Time : O(n) Space : O(n) */ void iterativePreorder() { cout<<"\nPREORDER:\n"; node* stack[50] ; stack[0] = NULL; int top = 0; node *ptr = root; while(1) { if(ptr != NULL) { cout<<" "<<ptr->getData(); stack[++top] = ptr; ptr = ptr->getLeftChild(); } else { ptr = stack[top--]; if( ptr == NULL) return; if(ptr->getRightChild()) ptr = ptr->getRightChild(); else ptr = NULL; } } }
Saturday, 4 May 2013
Non-Recursive implementation of Preorder Traversal in a binary Tree / BST.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment