SlideShare a Scribd company logo
10
Most read
D A T A S T R U C T U R E S
Tree:
So far, we have been studying mainly linear types of data structures: arrays,
lists, stacks and queues. Now we defines a nonlinear data structure called Tree. This
structure is mainly used to represent data containing a hierarchical relationship
between nodes/elements e.g. family trees and tables of contents.
There are two main types of tree:
 General Tree 
 Binary Tree 
General Tree: 
A tree where a node can has any number of children / descendants is called
General Tree. For example:

Following figure is an example of general tree where root is “Desktop”.
D A T A S T R U C T U R E S
Binary Tree:
A tree in which each element may has 0-child , 1-child or maximum of 2-children.
A Binary Tree T is defined as finite set of elements, called nodes, such that:
a) T is empty (called the null tree or empty tree.)
b) T contains a distinguished node R, called the root of T, and the remaining
nodes of T form an ordered pair of disjoint binary trees T1 and T2.
If T does contain a root R, then the two trees T1 and T2 are called, respectively, the
left sub tree and right sub tree of R.
D A T A S T R U C T U R E S
If T1 is non empty, then its node is called the left successor of R; similarly, if T 2 is
non empty, then its node is called the right successor of R. The nodes with no
successors are called the terminal nodes. If N is a node in T with left successor S1
and right successor S2, then N is called the parent(or father) of S1 and S2.
Analogously, S1 is called the left child (or son) of N, and S 2 is called the right child
(or son) of N. Furthermore, S1 and S2 are said to siblings (or brothers). Every
node in the binary tree T, except the root, has a unique parent, called the
predecessor of N. The line drawn from a node N of T to a successor is called an
edge, and a sequence of consecutive edges is called a path. A terminal node is
called a leaves, and a path ending in a leaves is called a branch.
The depth (or height) of a tree T is the maximum number of nodes in a
branch of T. This turns out to be 1 more than the largest level number of T.
Level of node & its generation:
Each node in binary tree T is assigned a level number, as follows. The root R
of the tree T is assigned the level number 0, and every other node is assigned a
level number which is 1 more than the level number of its parent. Furthermore,
those nodes with the same level number are said to belong to the same generation.
D A T A S T R U C T U R E S
Complete Binary Tree:
Consider a binary tree T. each node of T can have at most two children.
Accordingly, one can show that level n-2 of T can have at most two nodes.
A tree is said to be complete if all its levels, except possibly the last have the
maximum number of possible nodes, and if all the nodes at the last level appear as
far left as possible.
A
B E
F G L M
N O P
Extended Binary Tree: 2-Tree:
A binary tree T is said to be a 2-tree or an extended binary tree if each node
N has either 0 or 2 children.
In such a case, the nodes, with 2 children are called internal nodes, and the
node with 0 children are called external node.
A
A
B
B
Binary Tree Extended 2-tree
D A T A S T R U C T U R E S
Traversing of Binary Tree:
A traversal of a tree T is a systematic way of accessing or visiting all the node of T.
There are three standard ways of traversing a binary tree T with root R. these are :
 Preorder (N L R): 
a) Process the node/root. (A B D F I C G H J L K)
b) Traverse the Left sub tree.
c) Traverse the Right sub tree.
 Inorder (L N R): ( D B I F A G C L J H K )
a) Traverse the Left sub tree.
b) Process the node/root.
c) Traverse the Right sub tree.
 Postorder (L R N): ( D I F B G L J K H C A )
a) Traverse the Left sub tree.
b) Traverse the Right sub tree.
c) Process the node/root.
 Descending order (R N L): ( K H J L C G A F I B D )
(Used in Binary Search Tree, will be discussed later)
a) Traverse the Right sub tree.
b) Process the node/root.
c) Traverse the Left sub tree.
D A T A S T R U C T U R E S
Preorder Traversal:
Algorithm: PREORDER (pRoot)
First time this function is called by passing original root into pRoot.
Here pRoot is pointers pointing to current root. This algorithm does a
preorder traversal of T, applying by rcurrsively calling same function
and updating proot to traverse in a way i.e. (NLR) Node, Left, Right.
1. If (pRoot NOT = NULL) then: [ does child exist ?]
i- Apply PROCESS to pRoot-> info. e.g. Write: pRoot -> info
[ recursive call by passing address of left child to update pRoot]
ii- PREORDER (pRoot -> Left)
[ recursive call by passing address of right child to update pRoot]
iii- PREORDER( pRoot -> Right)
[End of If structure.]
2. Exit.
Inorder Traversal:
Algorithm: INORDER (pRoot)
First time this function is called by passing original root into pRoot.
Here pRoot is pointers pointing to current root. This algorithm does a
Inorder traversal of T, applying by rcurrsively calling same function
and updating proot to traverse in a way i.e. (LNR) Left, Node, Right.
1. If (pRoot NOT = NULL) then: [ does child exist ?]
[ recursive call by passing address of left child to update pRoot]
i- PREORDER (pRoot -> Left)
ii- Apply PROCESS to pRoot-> info. e.g. Write: pRoot -> info
[ recursive call by passing address of right child to update pRoot]
iii- PREORDER( pRoot ->
Right) [End of If structure.]
2. Exit.
Postorder Traversal:
Algorithm: POSTORDER (pRoot)
First time this function is called by passing original root into pRoot.
Here pRoot is pointers pointing to current root. This algorithm does a
Postorder traversal of T, applying by rcurrsively calling same function
and updating proot to traverse in a way i.e. (LRN) Left, Right, Node.
1. If (pRoot NOT = NULL) then: [ does child exist ?]
[ recursive call by passing address of left child to update pRoot]
i- PREORDER (pRoot -> Left)
[ recursive call by passing address of right child to update pRoot]
ii- PREORDER( pRoot -> Right)
iii- Apply PROCESS to pRoot-> info. e.g. Write: pRoot -> info
[End of If structure.]
2. Exit.
D A T A S T R U C T U R E S
Preparing a Tree from an infix arithmetic expression
Recursion:
For implementing tree traversal logics as stated, two approaches are used, i.e. use
stacks or recursive functions.
Recursion is an important concept in computer science. Many algorithms can be best
described in terms of recursion. A recursive function / procedure containing a Call
statement to itself. To make a function recursive one must consider the following
properties:
(1) There must be certain (using arguments), called base criteria, for which the
procedure / function does not call itself.
(2) Each time the procedure / function does call itself, control must be closer to
the base criteria.
D A T A S T R U C T U R E S
Binary Search Tree:
Suppose T is a binary tree, the T is called a binary search tree or binary
sorted tree if each node N of T has the following property:
The values of at N (node) is greater than every value in the left sub tree of
N and is less than every value in the right sub tree of N.
Binary Search Tree using these values: (50, 30, 55, 25, 10, 35, 37, 31, 20, 53, 60,
62)
 50 
 30

55

 25 35 53 60
 

10 62
31 37
20
Following figure shows a binary search tree. Notice that this tree is obtained by inserting
the values 13, 3, 4, 12, 14, 10, 5, 1, 8, 2, 7, 9, 11, 6, 18 in that order, starting from an
empty tree.
D A T A S T R U C T U R E S
 Sorting: Note that inorder traversal of a binary search tree always gives a sorted
sequence of the values. This is a direct consequence of the BST property. This
provides a way of sorting a given sequence of keys: first, create a BST with these
keys and then do an inorder traversal of the BST so created. 
Inorder Travers (LNR) : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 18 

 Search: is straightforward in a BST. Start with the root and keep moving left or
right using the BST property. If the key we are seeking is present, this search
procedure will lead us to the key. If the key is not present, we end up in a null
link. 
 Insertion in a BST is also a straightforward operation. If we need to insert an
element n, we traverse tree starting from root by considering the above stated
rules. Our traverse procedure ends in a null link. It is at this position of this null
link that n will be included. . 
 Deletion in BST: Let x be a value to be deleted from the BST and let N denote
the node containing the value x. Deletion of an element in a BST again uses the
BST property in a critical way. When we delete the node N containing x, it would
create a "gap" that should be filled by a suitable existing node of the BST. There
are two possible candidate nodes that can fill this gap, in a way that the BST
property is not violated: (1). Node containing highest valued element among all
descendants of left child of N. (2). Node containing the lowest valued element
among all the descendants of the right child of N. There are three possible cases to
consider: 
Deleting a leaf (node with no children): Deleting a leaf is easy, as we can
simply remove it from the tree. 
Deleting a node with one child: Delete it and replace it with its child. 
Deleting a node with two children: Call the node to be deleted "N". Do not
delete N. Instead, choose its in-order successor node "S". Replace the value of 
“N” with the value of “S”. (Note: S itself has up to one child.) 
As with all binary trees, a node's in-order successor is the left-most child of its
right subtree. This node will have zero or one child. Delete it according to one of
the two simpler cases above. 

Figure on next page illustrates several scenarios for deletion in BSTs. 
D A T A S T R U C T U R E S

More Related Content

What's hot (20)

PDF
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
PPTX
linked list in Data Structure, Simple and Easy Tutorial
Afzal Badshah
 
PPSX
Data Structure (Queue)
Adam Mukharil Bachtiar
 
PPT
Infix prefix postfix
Self-Employed
 
PDF
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
PDF
Binary tree
Rajendran
 
PPSX
Stack
Seema Sharma
 
PPT
Queue data structure
anooppjoseph
 
PPTX
Huffman's algorithm in Data Structure
Vrushali Dhanokar
 
PPTX
Queue in Data Structure
Janki Shah
 
PPTX
Infix to postfix conversion
Then Murugeshwari
 
PPTX
Doubly Linked List
Ninad Mankar
 
PPTX
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
PDF
Applications of stack
eShikshak
 
PPTX
Double Linked List (Algorithm)
Huba Akhtar
 
PDF
linked lists in data structures
DurgaDeviCbit
 
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Muhammad Hammad Waseem
 
PPTX
Row major and column major in 2 d
nikhilarora2211
 
PPTX
DFS and BFS
satya parsana
 
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
linked list in Data Structure, Simple and Easy Tutorial
Afzal Badshah
 
Data Structure (Queue)
Adam Mukharil Bachtiar
 
Infix prefix postfix
Self-Employed
 
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Binary tree
Rajendran
 
Queue data structure
anooppjoseph
 
Huffman's algorithm in Data Structure
Vrushali Dhanokar
 
Queue in Data Structure
Janki Shah
 
Infix to postfix conversion
Then Murugeshwari
 
Doubly Linked List
Ninad Mankar
 
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
Applications of stack
eShikshak
 
Double Linked List (Algorithm)
Huba Akhtar
 
linked lists in data structures
DurgaDeviCbit
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Muhammad Hammad Waseem
 
Row major and column major in 2 d
nikhilarora2211
 
DFS and BFS
satya parsana
 

Viewers also liked (15)

PDF
Consultores para la Reactivación Económica y el Autoempleo
David Solves
 
PDF
Electrical power Engineer
Ibrahim Mahmoud
 
PPTX
AggelikiLamprou1053460, StellaAnagnostopoulou1053396
aggeliki lamp
 
PPTX
Los mandatos
nickclift
 
DOCX
Term paper
orderyouressays
 
PPTX
Definiciones de conceptos (tic's)
Eduardo Vea Royo
 
PDF
Ganadores direct latinoamericanos cannes lions 2015
letskalk
 
PPTX
Ppt akhlaq
anniemasni123
 
PPTX
Ppt akhlaq
anniemasni123
 
PDF
Fine Homes Summer 2013 Article
Nathan Stobbe
 
PDF
El cambio-educativo-desde-la-investigacion-accion. elliot
Hermila A
 
PDF
2016 - Femi Osofisan's Vagabond Minstrels
KemiIlori
 
PPTX
Pp fundamentos
CarmenSlideSH
 
Consultores para la Reactivación Económica y el Autoempleo
David Solves
 
Electrical power Engineer
Ibrahim Mahmoud
 
AggelikiLamprou1053460, StellaAnagnostopoulou1053396
aggeliki lamp
 
Los mandatos
nickclift
 
Term paper
orderyouressays
 
Definiciones de conceptos (tic's)
Eduardo Vea Royo
 
Ganadores direct latinoamericanos cannes lions 2015
letskalk
 
Ppt akhlaq
anniemasni123
 
Ppt akhlaq
anniemasni123
 
Fine Homes Summer 2013 Article
Nathan Stobbe
 
El cambio-educativo-desde-la-investigacion-accion. elliot
Hermila A
 
2016 - Femi Osofisan's Vagabond Minstrels
KemiIlori
 
Pp fundamentos
CarmenSlideSH
 
Ad

Similar to Lecture notes data structures tree (20)

PPTX
Unit-VStackStackStackStackStackStack.pptx
nakshpub
 
PDF
481803111-Trees-Unit-Review-pdf - Copy.pdf
barsubiasarah
 
PPT
Lecture 5 tree.pptx
Abirami A
 
PPTX
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
sahadevbkbiet2023
 
PPTX
7.tree
Chandan Singh
 
PDF
Dsc++ unit 3 notes
Guru Nanak Institute Of Tech
 
PPTX
Tree.pptx
worldchannel
 
PPT
Tree and Binary Search tree
Muhazzab Chouhadry
 
PPT
Unit 4 tree
kalyanineve
 
PPTX
BCS304 Module 3 Slide 29-61.pptx DSA notes 3rd sem
ticonah393
 
PPTX
Data Structures and Algorithms - Lecture 10 - Thushapan.pptx
timspizer25
 
PPTX
non linear data structure -introduction of tree
Siddhi Viradiya
 
PPTX
Tree
bhumish
 
PPTX
Trees in Data Structure
Om Prakash
 
PPT
ds 10-Binary Tree.ppt
khitishlpu
 
PPT
Unit 3.ppt
JITTAYASHWANTHREDDY
 
PDF
(a)PreOrder, PostOrder and Inorder are three ways you can iterate .pdf
ANANDSHOE
 
PPT
Data Structure And Algorithms for Computer Science
ManishShukla712917
 
PPT
Data Structure and Algorithms Binary Tree
ManishPrajapati78
 
Unit-VStackStackStackStackStackStack.pptx
nakshpub
 
481803111-Trees-Unit-Review-pdf - Copy.pdf
barsubiasarah
 
Lecture 5 tree.pptx
Abirami A
 
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
sahadevbkbiet2023
 
Dsc++ unit 3 notes
Guru Nanak Institute Of Tech
 
Tree.pptx
worldchannel
 
Tree and Binary Search tree
Muhazzab Chouhadry
 
Unit 4 tree
kalyanineve
 
BCS304 Module 3 Slide 29-61.pptx DSA notes 3rd sem
ticonah393
 
Data Structures and Algorithms - Lecture 10 - Thushapan.pptx
timspizer25
 
non linear data structure -introduction of tree
Siddhi Viradiya
 
Tree
bhumish
 
Trees in Data Structure
Om Prakash
 
ds 10-Binary Tree.ppt
khitishlpu
 
(a)PreOrder, PostOrder and Inorder are three ways you can iterate .pdf
ANANDSHOE
 
Data Structure And Algorithms for Computer Science
ManishShukla712917
 
Data Structure and Algorithms Binary Tree
ManishPrajapati78
 
Ad

More from maamir farooq (20)

DOCX
Ooad lab1
maamir farooq
 
PPT
Lesson 03
maamir farooq
 
PPT
Lesson 02
maamir farooq
 
PDF
Php client libray
maamir farooq
 
PDF
Swiftmailer
maamir farooq
 
PDF
Lect15
maamir farooq
 
PDF
Lec 7
maamir farooq
 
PPTX
Lec 6
maamir farooq
 
PDF
Lec 5
maamir farooq
 
PDF
J query 1.7 cheat sheet
maamir farooq
 
PDF
Assignment
maamir farooq
 
PDF
Java script summary
maamir farooq
 
PDF
Lec 3
maamir farooq
 
PDF
Lec 2
maamir farooq
 
PPTX
Lec 1
maamir farooq
 
PPTX
Css summary
maamir farooq
 
DOCX
Manual of image processing lab
maamir farooq
 
PDF
Session management
maamir farooq
 
PDF
Data management
maamir farooq
 
PPTX
Content provider
maamir farooq
 
Ooad lab1
maamir farooq
 
Lesson 03
maamir farooq
 
Lesson 02
maamir farooq
 
Php client libray
maamir farooq
 
Swiftmailer
maamir farooq
 
J query 1.7 cheat sheet
maamir farooq
 
Assignment
maamir farooq
 
Java script summary
maamir farooq
 
Css summary
maamir farooq
 
Manual of image processing lab
maamir farooq
 
Session management
maamir farooq
 
Data management
maamir farooq
 
Content provider
maamir farooq
 

Recently uploaded (20)

PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PDF
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PDF
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PPTX
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
community health nursing question paper 2.pdf
Prince kumar
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
Dimensions of Societal Planning in Commonism
StefanMz
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 

Lecture notes data structures tree

  • 1. D A T A S T R U C T U R E S Tree: So far, we have been studying mainly linear types of data structures: arrays, lists, stacks and queues. Now we defines a nonlinear data structure called Tree. This structure is mainly used to represent data containing a hierarchical relationship between nodes/elements e.g. family trees and tables of contents. There are two main types of tree:  General Tree   Binary Tree  General Tree:  A tree where a node can has any number of children / descendants is called General Tree. For example:  Following figure is an example of general tree where root is “Desktop”.
  • 2. D A T A S T R U C T U R E S Binary Tree: A tree in which each element may has 0-child , 1-child or maximum of 2-children. A Binary Tree T is defined as finite set of elements, called nodes, such that: a) T is empty (called the null tree or empty tree.) b) T contains a distinguished node R, called the root of T, and the remaining nodes of T form an ordered pair of disjoint binary trees T1 and T2. If T does contain a root R, then the two trees T1 and T2 are called, respectively, the left sub tree and right sub tree of R.
  • 3. D A T A S T R U C T U R E S If T1 is non empty, then its node is called the left successor of R; similarly, if T 2 is non empty, then its node is called the right successor of R. The nodes with no successors are called the terminal nodes. If N is a node in T with left successor S1 and right successor S2, then N is called the parent(or father) of S1 and S2. Analogously, S1 is called the left child (or son) of N, and S 2 is called the right child (or son) of N. Furthermore, S1 and S2 are said to siblings (or brothers). Every node in the binary tree T, except the root, has a unique parent, called the predecessor of N. The line drawn from a node N of T to a successor is called an edge, and a sequence of consecutive edges is called a path. A terminal node is called a leaves, and a path ending in a leaves is called a branch. The depth (or height) of a tree T is the maximum number of nodes in a branch of T. This turns out to be 1 more than the largest level number of T. Level of node & its generation: Each node in binary tree T is assigned a level number, as follows. The root R of the tree T is assigned the level number 0, and every other node is assigned a level number which is 1 more than the level number of its parent. Furthermore, those nodes with the same level number are said to belong to the same generation.
  • 4. D A T A S T R U C T U R E S Complete Binary Tree: Consider a binary tree T. each node of T can have at most two children. Accordingly, one can show that level n-2 of T can have at most two nodes. A tree is said to be complete if all its levels, except possibly the last have the maximum number of possible nodes, and if all the nodes at the last level appear as far left as possible. A B E F G L M N O P Extended Binary Tree: 2-Tree: A binary tree T is said to be a 2-tree or an extended binary tree if each node N has either 0 or 2 children. In such a case, the nodes, with 2 children are called internal nodes, and the node with 0 children are called external node. A A B B Binary Tree Extended 2-tree
  • 5. D A T A S T R U C T U R E S Traversing of Binary Tree: A traversal of a tree T is a systematic way of accessing or visiting all the node of T. There are three standard ways of traversing a binary tree T with root R. these are :  Preorder (N L R):  a) Process the node/root. (A B D F I C G H J L K) b) Traverse the Left sub tree. c) Traverse the Right sub tree.  Inorder (L N R): ( D B I F A G C L J H K ) a) Traverse the Left sub tree. b) Process the node/root. c) Traverse the Right sub tree.  Postorder (L R N): ( D I F B G L J K H C A ) a) Traverse the Left sub tree. b) Traverse the Right sub tree. c) Process the node/root.  Descending order (R N L): ( K H J L C G A F I B D ) (Used in Binary Search Tree, will be discussed later) a) Traverse the Right sub tree. b) Process the node/root. c) Traverse the Left sub tree.
  • 6. D A T A S T R U C T U R E S Preorder Traversal: Algorithm: PREORDER (pRoot) First time this function is called by passing original root into pRoot. Here pRoot is pointers pointing to current root. This algorithm does a preorder traversal of T, applying by rcurrsively calling same function and updating proot to traverse in a way i.e. (NLR) Node, Left, Right. 1. If (pRoot NOT = NULL) then: [ does child exist ?] i- Apply PROCESS to pRoot-> info. e.g. Write: pRoot -> info [ recursive call by passing address of left child to update pRoot] ii- PREORDER (pRoot -> Left) [ recursive call by passing address of right child to update pRoot] iii- PREORDER( pRoot -> Right) [End of If structure.] 2. Exit. Inorder Traversal: Algorithm: INORDER (pRoot) First time this function is called by passing original root into pRoot. Here pRoot is pointers pointing to current root. This algorithm does a Inorder traversal of T, applying by rcurrsively calling same function and updating proot to traverse in a way i.e. (LNR) Left, Node, Right. 1. If (pRoot NOT = NULL) then: [ does child exist ?] [ recursive call by passing address of left child to update pRoot] i- PREORDER (pRoot -> Left) ii- Apply PROCESS to pRoot-> info. e.g. Write: pRoot -> info [ recursive call by passing address of right child to update pRoot] iii- PREORDER( pRoot -> Right) [End of If structure.] 2. Exit. Postorder Traversal: Algorithm: POSTORDER (pRoot) First time this function is called by passing original root into pRoot. Here pRoot is pointers pointing to current root. This algorithm does a Postorder traversal of T, applying by rcurrsively calling same function and updating proot to traverse in a way i.e. (LRN) Left, Right, Node. 1. If (pRoot NOT = NULL) then: [ does child exist ?] [ recursive call by passing address of left child to update pRoot] i- PREORDER (pRoot -> Left) [ recursive call by passing address of right child to update pRoot] ii- PREORDER( pRoot -> Right) iii- Apply PROCESS to pRoot-> info. e.g. Write: pRoot -> info [End of If structure.] 2. Exit.
  • 7. D A T A S T R U C T U R E S Preparing a Tree from an infix arithmetic expression Recursion: For implementing tree traversal logics as stated, two approaches are used, i.e. use stacks or recursive functions. Recursion is an important concept in computer science. Many algorithms can be best described in terms of recursion. A recursive function / procedure containing a Call statement to itself. To make a function recursive one must consider the following properties: (1) There must be certain (using arguments), called base criteria, for which the procedure / function does not call itself. (2) Each time the procedure / function does call itself, control must be closer to the base criteria.
  • 8. D A T A S T R U C T U R E S Binary Search Tree: Suppose T is a binary tree, the T is called a binary search tree or binary sorted tree if each node N of T has the following property: The values of at N (node) is greater than every value in the left sub tree of N and is less than every value in the right sub tree of N. Binary Search Tree using these values: (50, 30, 55, 25, 10, 35, 37, 31, 20, 53, 60, 62)  50   30  55   25 35 53 60    10 62 31 37 20 Following figure shows a binary search tree. Notice that this tree is obtained by inserting the values 13, 3, 4, 12, 14, 10, 5, 1, 8, 2, 7, 9, 11, 6, 18 in that order, starting from an empty tree.
  • 9. D A T A S T R U C T U R E S  Sorting: Note that inorder traversal of a binary search tree always gives a sorted sequence of the values. This is a direct consequence of the BST property. This provides a way of sorting a given sequence of keys: first, create a BST with these keys and then do an inorder traversal of the BST so created.  Inorder Travers (LNR) : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 18    Search: is straightforward in a BST. Start with the root and keep moving left or right using the BST property. If the key we are seeking is present, this search procedure will lead us to the key. If the key is not present, we end up in a null link.   Insertion in a BST is also a straightforward operation. If we need to insert an element n, we traverse tree starting from root by considering the above stated rules. Our traverse procedure ends in a null link. It is at this position of this null link that n will be included. .   Deletion in BST: Let x be a value to be deleted from the BST and let N denote the node containing the value x. Deletion of an element in a BST again uses the BST property in a critical way. When we delete the node N containing x, it would create a "gap" that should be filled by a suitable existing node of the BST. There are two possible candidate nodes that can fill this gap, in a way that the BST property is not violated: (1). Node containing highest valued element among all descendants of left child of N. (2). Node containing the lowest valued element among all the descendants of the right child of N. There are three possible cases to consider:  Deleting a leaf (node with no children): Deleting a leaf is easy, as we can simply remove it from the tree.  Deleting a node with one child: Delete it and replace it with its child.  Deleting a node with two children: Call the node to be deleted "N". Do not delete N. Instead, choose its in-order successor node "S". Replace the value of  “N” with the value of “S”. (Note: S itself has up to one child.)  As with all binary trees, a node's in-order successor is the left-most child of its right subtree. This node will have zero or one child. Delete it according to one of the two simpler cases above.   Figure on next page illustrates several scenarios for deletion in BSTs. 
  • 10. D A T A S T R U C T U R E S