DSA Lec 7
DSA Lec 7
Trees
Course Instructor
Engr. Anum Raza
Lecture Outline
Traversal Techniques
Preorder with algorithm
Postorder with algorithm
Expressions using Trees
Binary Search Tree (BST)
Searching in BST
Preorder Traversal
Root Left Right manner
+
+ Left Right
+ [*Left Right] [+Left Right] * +
+(*AB) [+ *Left Right E]
+*AB + *C D E A B * E
C D
Algorithm for Preorder Traversal
1) Set Top=1, Stack[Top]=NULL and Ptr=Root
2) Repeat Step 3 to 5 while (Ptr ≠ NULL)
3) Apply process to Data[Ptr]
4) If Right[Ptr] ≠ NULL [then Push on Stack]
Set Top=Top+1 and Stack[Top]=Right[Ptr]
5) If Left[Ptr]≠NULL then
Ptr=Left[Ptr] A
Else [Pop from Stack]
B C
Set Ptr=Stack[Top] and Top=Top-1
6) Exit
D E
Postorder Traversal
Left Right Root manner
+
Left Right + * +
[Left Right *] [Left Right+] +
(AB*) [Left Right * E + ]+ A B * E
(AB*) [C D * E + ]+
AB* C D * E + + C D
Algorithm for Postorder Traversal
1) Set Top=1, Stack[Top]=NULL, Ptr=Root
2) Repeat Step 3 to 5 while Ptr ≠ NULL
3) Set Top=Top+1 and Stack[Top]=Ptr
4) If Right[Ptr] ≠ NULL
Set Top=Top+1 and Stack[Top]=-Right[Ptr]
5) Set Ptr=Left[Ptr]
[End of Step 2]
A
6) Set Ptr=Stack[Top] and Top=Top-1
7) Repeat while Ptr>0 B C
a) Apply process to Data[Ptr]
Set Ptr= Stack[Top] and Top=Top-1
D E
8) if Ptr<0
a) Set Ptr=-Ptr
Go to Step 2
9) Exit
Expression Trees
(a+b*c) +((d*e+f)*g)
Convert : (a-b)/((c*d)+e)
Binary Search Tree
For every node, X, in the tree,
the values of all the keys in its left subtree are smaller than
the key value of X,
the values of all the keys in its right subtree are larger than
the key value of X.
X
Example
X>Y
X<Z
Y Z
Binary Search Trees
Examples
5
10 10
2 45
5 30 5 45
30
2 25 45 2 25 30
10
25
Binary search Not a binary
trees search tree
Binary Search Tree Operations
There are many operations one can perform on a binary search tree.
We will briefly cover all of these operations with their general algorithms
Implementation and examples.
Creating a Binary (Search) Tree
The root pointer is the pointer to the binary tree.
This is similar to the head pointer in a linked list.
root
10 5
10 > 2, left 5 > 2, left
5 30 5 > 2, left 2 45 2 = 2, found
2 = 2, found
2 25 45 30
10
25
Example Binary Searches
Find ( 25 )
10 5
10 < 25, right 5 < 25, right
5 30 30 > 25, left 2 45 45 > 25, left
25 = 25, found 30 > 25, left
2 25 45 30
10 < 25, right
10 25 = 25, found
25
Algorithm for Searching in BST
1) If (Root=NULL) Loc = NULL and Exit
2) If (Item= Data[Root]) Loc = Root and Exit
3) If (Item< Data[Root])
Ptr=Left(Root)
Else
Ptr=Right(Root) 20
4) Repeat while (Ptr ≠ NULL)
If (Item= Data[Ptr])
15 30
Loc = Ptr and Exit
Else If (Item < Data [Ptr])
Ptr= Left [Ptr] 10 18 25 35
Else
Ptr=Right[Ptr]
5) Loc= NULL
6) Exit
Insertion in BST
Figure shows the structure of the binary tree built by the program.
20