DSA Lec 6
DSA Lec 6
Trees
Course Instructor
Engr. Anum Raza
Lecture Outline
Trees
Basic Terminologies
Tree Properties
Binary Tree
Trees
Hierarchical data structure
Examples:
Indexes in a book have a shallow tree structure
A family tree
Others?
Unix / Windows file structure
Trees: Basic terminology[1]
Hierarchical data structure
Each position in the tree is called a node
The “top” of the tree is called the root
The nodes immediately below a node are called its children; nodes with
no children are called leaves (or terminal nodes), and the node above
a given node is its parent (or father)
Node A Node B
H I
Binary Trees
A commonly used type of tree is a binary tree
Each node has at most two children
12
Tree ADT
Objects: any type of objects can be stored in a tree
accessor methods
root() – return the root of the tree
parent(p) – return the parent of a node
children(p) – returns the children of a node
query methods
size() – returns the number of nodes in the tree
isEmpty() - returns true if the tree is empty
elements() – returns all elements
isRoot(p), isInternal(p), isExternal(p)
other methods
Tree traversal, Node addition/deletion, create/destroy
Lecture 6b
Lecture Outline
Binary Tree
Storage Techniques
Traversal Techniques
Inorder with algorithm
Binary Trees Storage
Linked List based implementation
Array based implementation
Binary Tree: contiguous storage
Value in root node stored first, followed by left child, then
right child
Each successive level in the tree stored left to right;
unused nodes in tree represented by a bit pattern to
indicate nothing stored there
A
[1] A
[2] B
[3] --
B
[4] C
[5] --
C [6] --
[7] --
D [8] D
[9] --
. .
E
[16] E
A
B C
[1] A
[2] B
D E F G
[3] C
[4] D
[5] E
H I [6] F
[7] G
[8] H
[9] I
Binary Tree: as a linked structure
Each node in the tree consists of:
The data, or value contained in the element
A left child pointer (pointer to first child)
A right child pointer (pointer to second child)
Binary Tree: as a linked structure
A root pointer points to the root node
Follow pointers to find every other element in the tree
Add and remove nodes by manipulating pointers
Leaf nodes have child pointers set to null
class CBinTree
{
struct Node
{
int value;
Node *LeftChild,*RightChild;
}*Root;
/***Operations*********/
/************************/
};
a
b c
d e f
g h i j k
l
24
Traversal of Binary Trees
Pass through all nodes of tree
Inorder (symmetric traversal)
Preorder (depth first traversal)
Postorder
Trees Traversal
Inorder
Root
(Left) Root (Right)
Preorder
Left Right
Root (Left) (Right)
Postorder
(Left) (Right) Root
Inorder Traversal
Left Root Right manner
+
Left + Right * +
[Left*Right]+[Left+Right]
(A*B)+[(Left*Right)+E) A B * E
(A*B)+[(C*D)+E]
C D
(A*B)+(C*D+E)
Algorithm for Inorder Traversal
[push NULL onto stack and initialize PTR]
1) Set Top=1, Stack[1]=NULL and Ptr=Root
2) Repeat while (Ptr ≠ NULL)
Top=Top+1, Stack[Top]=Ptr (Pushes left most path onto Stack)
Ptr=Left[Ptr]