Logo 
Search:

C++ Programming FAQ

Submit Interview FAQ
Home » Interview FAQ » C++ ProgrammingRSS Feeds

Iterative algorithm for traversing a binary tree in preorder in dfs (data file structure).

  Shared By: Sophia Hughes    Date: Jun 10    Category: C++ Programming    Views: 2295

Answer:

PROCEDURE PREORDER(T)
[Given a binary tree whose root node address is given by the pointer variable T, this algorithm traverses the tree in preorder in an iterative manner].

1. [Initialize]

If T = NULL
then write (“Empty Tree”)
return
else
TOP <-- 0.

2. [Process each stack branch address]

Repeat step 3 while TOP > 0.

3. [Get stored address and branch left]

flag <-- 0
while T != NULL
while flag != 1
call push(S,TOP,T)
write DATA(D)
T <-- LPTR(T)
if T = NULL
flag <-- 1.

4. [Traverse the right side]

D <-- pop(S,TOP)
T <-- RPTR(D)
flag <-- 0
while T =NULL
D <-- POP(S,TOP)
T <-- RPTR(D)
if TOP = 0
return.

5. [FINISH]
return.

Share: 
 



Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: