Menu

[Solved]Question 1 Non Recursive Order Traverse Binary Tree Using Stack Obvious Way Traverse Tree Q37028837

Question 1: Non-recursive In-order traverse of a binary treeUsing Stack is the obvious way to traverse tree without recursion.Below is an algorithm for traversing binary tree using stack. Seethis for step wise step execution of the algorithm. 1) Create anempty stack S. 2) Initialize current node as root 3) Push thecurrent node to S and set current = current->left until currentis NULL 4) If current is NULL and stack is not empty then a) Popthe top item from stack. b) Print the popped item, set current =popped_item->right c) Go to step 3. 5) If current is NULL andstack is empty then we are done. Let us consider the below tree forexample 1 / 2 3 / 4 5 Step 1 Creates an empty stack: S = NULLStep 2 sets current as address of root: current -> 1 Step 3Pushes the current node and set current = current->left untilcurrent is NULL current -> 1 push 1: Stack S -> 1 current-> 2 push 2: Stack S -> 2, 1 current -> 4 push 4: Stack S-> 4, 2, 1 current = NULL Step 4 pops from S a) Pop 4: Stack S-> 2, 1 b) print “4” c) current = NULL /*right of 4 */ and go tostep 3 Since current is NULL step 3 doesn’t do anything. Step 4pops again. a) Pop 2: Stack S -> 1 b) print “2” c) current ->5/*right of 2 */ and go to step 3 Step 3 pushes 5 to stack andmakes current NULL Stack S -> 5, 1 current = NULL Step 4 popsfrom S a) Pop 5: Stack S -> 1 b) print “5” c) current = NULL/*right of 5 */ and go to step 3 Since current is NULL step 3doesn’t do anything Step 4 pops again. a) Pop 1: Stack S -> NULLb) print “1” c) current -> 3 /*right of 5 */ Step 3 pushes 3 tostack and makes current NULL Stack S -> 3 current = NULL Step 4pops from S a) Pop 3: Stack S -> NULL b) print “3” c) current =NULL /*right of 3 */ Traversal is done now as stack S is empty andcurrent is NULL. Write a non-recursive application for the in-ordertraverse for a binary tree. In Java

Expert Answer


Answer to Question 1: Non-recursive In-order traverse of a binary tree Using Stack is the obvious way to traverse tree without rec… . . .

OR


Leave a Reply

Your email address will not be published. Required fields are marked *