Sunday, 11 September 2011

A brief summary of Binary Tree PreOrder (Recursive and Non - Recursive) Implementaion

PreOrder traversal: Is a method of visiting all nodes of a Binary tree where the Root of the given node is traversed first followed by the Left child and then the Right child of the node. The term Pre refers to the position of the ROOT in the traversal result. The ROOT of the tree is the first element in the result of this traversal.

The logic involved in the implementation of the solution is in the comments of the below code.
Just one point which i need to mention about solving recursive problems in a non recursive method involves
two indispensable ingredients for the solution u cook i) Stack, ii) While Loop.



/* Wraper function to call either of the PreOrder implementations, Recursive/Non-Recursive. Function accepts a boolean and whe ever its true the recursive method is invoked else non-recursive method. */ void LintkedIntTree::preOrder(bool isRecursive) { if(isRecursive==true) { this->preOrderRec(root); } else{ StacktNode* temp = new StacktNode(root,NULL); StackInt* stack = new StackInt(temp,1); this->preOrderNonRec(stack); } return; } /* Recursive method is simple if understand the recursive paradigm. Currently the function just prints the traversal result, An vector can be used to store the traversal and return the result. Logic: the node being visited is printed out first later its left child is passesd and then the right child. */ void LintkedIntTree::preOrderRec(BinaryTreeIntNode* node) { if(node == NULL){return;} cout<<" "<<node->data; preOrderRec(node->left); preOrderRec(node->right); return; } /* When ever we are asked to implementat a Recursively solvable problem with a non Recursive solution, Two things will become in dispensable i) Stack and ii) While loop. Logic: Push the Root on the Stack. While the stack is not empty pop the node print the value if right child not NULL push right if left child not null push the left loop end. Note we push the right child first as Stack is a LIFO structure, hence left child is oped out first by pusing right followed by left child. */ void LintkedIntTree::preOrderNonRec(StackInt* stack) { while(!stack->isEmpty()) { StacktNode* temp = stack->pop(); if(temp == NULL) { continue; } else { cout<<" "<<temp->node->data; if(temp->node->right!= NULL) { StacktNode* right = new StacktNode(temp->node->right,NULL); stack->push(right); } if(temp->node->left!= NULL) { StacktNode* left = new StacktNode(temp->node->left,NULL); stack->push(left); } } temp->~StacktNode(); } return; }

No comments:

Post a Comment