faqts : Computers : Programming : Algorithms : Datastructure : Graph : Tree : Binary tree

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

16 of 22 people (73%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

Datastructure: Tree: Binary: Print: Recursion: How to print a binary tree?

Feb 5th, 2005 12:04
Knud van Eeden,


----------------------------------------------------------------------
--- Knud van Eeden --- 23 October 2003 - 10:52 pm --------------------

Datastructure: Tree: Binary: Print: Recursion: How to print a binary 
tree?

---

Given the expression

  3 + 4

stored in a binary tree.

---

The easiest and shortest methods are the recursive print routines.

---

Here a binary tree printing program in pseudocode

---

PROC binaryprint( pointer P, integer depthI )
//
IF P == nill
 RETURN()
ENDIF
//
// 3 possibilities: PREFIX, INFIX, or SUFFIX print order
//
binaryprint( P.leftP, depthI + 1 )
//
binaryprintresult( P )
//
binaryprint( P.rightP, depthI + 1 )
//
END

PROC binaryprintresult( pointer P )
 Message( P )
 // Message( P.leftP )
 // Message( P.rightP )
 // Message( depthI )
END

PROC Main()
 binaryprint( rootP, 0 )
END

---
---

Note:

You have 3 ways to traverse or walk the tree:

prefix, infix, or suffix.

---

A. PREFIX printing

---

Then you can get prefix printing
with this order of source lines in your source code (so put the line 
that prints, 'binaryprintresult()' on first line)

binaryprintresult( P )
//
binaryprint( P.leftP, depthI + 1 )
//
binaryprint( P.rightP, depthI + 1 )

---

So that will print + 3 4

---

B. INFIX printing

---

Then you can get infix printing
with this order of source lines in your source code (so put the line 
that prints, 'binaryprintresult()' on second line)

binaryprint( P.leftP, depthI + 1 )
//
binaryprintresult( P )
//
binaryprint( P.rightP, depthI + 1 )

---

So that will print 3 + 4

---

C. SUFFIX printing

Then you can get suffix printing
with this order of source lines in your source code (so put the line 
that prints, 'binaryprintresult()' on third line)

binaryprint( P.leftP, depthI + 1 )
//
binaryprint( P.rightP, depthI + 1 )
//
binaryprintresult( P )

---

So that will print 3 4 +

---
---

Internet: see also:

---

Datastructure: Link: Overview: Can you give an overview of links?
http://www.faqts.com/knowledge_base/view.phtml/aid/32054/fid/1264

----------------------------------------------------------------------