Unit IV
Unit IV
Definition:
• A tree is a set of nodes that is either empty or
has a designated node called the root from which
hierarchically descend zero or more subtrees, which are
also trees.
Example:
Binary Trees
A binary tree is a tree in which no node can have
more than two subtrees . That is a node can have
zero, one or two subtrees which are called left
subtree and a right subtree.
Each subtree is a binary tree by itself.
Complete tree: A complete tree has the
maximum number of entries for it’s height. It is
reached when the last level is full. A tree is
considered nearly complete if all the nodes in
the last level are found on the left.
Memory Representation
Two ways:
1. Array representation
2. Linked list representation
Array representation
Example:
Disadvantage: More memory is needed to
represent the tree.
Linked list representation
• Uses three parallel arrays (INFO, LEFT and
RIGHT)
• Pointer variable ROOT which will contain the
location of the root R of tree, T
• INFO[K] contains the data at the node N
• LEFT[K] contains the location of the left child
of N
• RIGHT[K] contains the location of the right
child of N
Advantage:
1. Direct access to the root as well as children
node.
2. Memory is not wasted.
Example:
Inorder Traversal(LNR)
Algorithm Inorder(val root <node pointer>)
This algorithm traverses a binary tree in left-node
right sequence
Pre: Root is the entry node of the tree or subtree
Post: Each node has been processed in inorder
1. If (root is not null)
1. Inorder (Root->left subtree)
2. Process (Root)
3. Inorder (Root->right subtree)
2. Endif
3. Return
End Inorder
Example:
Post order Traversal(LRN)
Algorithm Postorder (val root <node pointer>)
This algorithm traverses a binary tree in left- right
node sequence
Pre: Root is the entry node of the tree or subtree.
Post: Each node has been processed in postorder.
If (root is not null)
1. Postorder (Root->left subtree)
2. Postorder (Root->right subtree)
3. Process (Root)
2. Endif
3. Return
End Postorder
Example:
Expression trees
One of the applications of a binary tree is expression
tree. An expression tree is a binary tree with the
following properties.
– Each leaf is an operand
– The root and the internal nodes are operators.
– Subtrees are subexpressions with the root being
an operator.
A given arithmetic expression can be represented in the
form of a tree.
Ex. (a * (b + c) )+ d
Expression trees
+
a +
b c d
Expression trees
- +
a b *
c d e
p+(q*r)/((s-t*u)^a)/b /
+ -
* *
P q r s t u a b
Problems
1.The following prefix expression is given. Draw
the expression tree and find the infix and
postfix expressions.
*-AB+* CD/ EF
2. The following postfix expression is given.
Draw the expression tree and find the infix
and prefix expressions.
AB * CD/+ EF-*
Problems
Given
Preorder : A B D E C F
Inorder: D B E A C F
Construct the binary tree.
Problems
Given
Preorder: AB D E F C G H J L K
Inorder: D B F E A G C L J H K
Construct the binary tree. What is the balance
factor?
Problems
Given
Preorder : AB D E F G H I C J K L
Inorder: D B F H G I E A C K J L
Construct the binary tree and also derive its post
order.
Problems
Given
Pre: G B Q A C K F P D E R H
In: Q B K C F A G P E D H R
Problems
• A binary tree has 10 nodes. The inorder and
preorder traversal of the tree are shown
below. Draw the tree.
• Preorder: JCBADEFIGH
• Inorder: ABCEDFJGIH
Breadth First Traversal
4. if (not emptyQueue)
1. dequeue ( pointer)
5. else
1. pointer = null
3 return
end breadthFirst
Binary Search tree
Definition
A Binary Search tree is a Binary tree with the
following properties.
• All items on the LST are less than the root
• All items on the RST are greater or equal to
the root.
• Each Subtree is a binary search tree itself.
Why a BST ?
Array :Efficient for Binary search, but expensive
for insertion/deletion
Linked list: Efficient for insertion/deletion but
inefficient for search
50 38 44 22 77 35 60 90
Operations on BST
BST Traversals: Three kinds of traversals are
possible. Here we are interested in results of
traversals(Like In order method).
Example:
Consider the tree that is constructed and
traverse in inorder.
What do we get???
Ans: Sorted list.
44 30 50 22 60 55 77 55
Inserting into a heap
Algorithm Insheap
This algorithm adds a new element into a heap.
Pre: Item is the new item to be added.
Post: Heap is being constructed
1. Set N=N+1, PTR=N //Add new node to H
and initialize PTR
2. Loop (PTR>1) // Find location to insert the item
1. PAR=[PTR/2]
2. if (Item<=Tree[PAR])
1 Tree[PTR]=Item and Return
3. Endif
4. Tree[PTR]=Tree[PAR]
5. PTR=PAR //updating PTR
3. endloop
4. Tree[1]=Item //assigning item as the root of H
5. Return
Deleting the root of the heap
Let H be a heap with “N” Elements and Root is
“R” to be deleted.
1. We assign R to an Item
2. Replace R by the last node L of H so that H is
still a complete binary tree ,but may not be a
heap.
3. Reheap – Replace L into it’s appropriate
place.
Example
95 85 70 55 33 30 65 15 20 15 22
Algorithm
Algorithm Delheap
This algorithm assigns the root to a variable called Item
and then reheaps the remaining elements. LAST
saves the value of the original last node of H.
1. Item=Tree[1]
2. LAST=Tree[N] and N=N-1 //Remove the last node
3. PTR=1, Left=2, Right=3 // Initialize
4. Loop (Right<=N)
1.if (Last>=Tree[left] and last>=Tree[Right]
1. Tree[PTR]=Last and return
2.Endif
3. If ( Tree[Right]<=Tree[Left] )
1. Tree[PTR]=Tree[left]
2. PTR=Left
Else
1. Tree[PTR]=Tree[Right]
2. PTR=Right
4. Endif
5. Left=PTR *2 and Right=Left+1
6.endloop
7. If (Left=N and Last<Tree[Left])
1. PTR=Left
8. Tree[PTR]=Last
9. Return
Applications of a heap
1. Application to sorting
1. root->right = AVLinsert(root->right,newptr,taller)
2. if (taller) //rightsubtree is taller
1. if (root is LH)
1. taller=false
2. root->bal = even-high
2. else if (root is EH)
1. root->bal= right-high
3. else
1. root= rightbalance(root,taller)
4. endif
3. endif
5. endif
6.Return root
End AVL insert
Rotating Algorithm
Rotate Right
Algorithm RotateRight (Root)
This algorithm exchanges pointers to rotate the tree
right.
1. TempPtr=Root->Left
2. Root->Left=TempPtr->Right
3. TempPtr->Right=Root
4. Root=TempPtr
5. return
Example tree
Rotating Algorithm
Rotate Left
Algorithm RotateLeft (Root)
This algorithm exchanges pointers to rotate the tree
left.
1. TempPtr=Root->Right
2. Root->Right=TempPtr->Left
3. TempPtr->Left=Root
4. Root=TempPtr
5. return
Example tree
Left Balance Algorithm
Algorithm Left Balance
This algorithm is entered when the root is left heavy (that is the
left subtree is higher than the right subtree)
Pre: root is a pointer to the root of the tree
taller is true
Post: root has been updated (if necessary)
taller has been updated
1. Lefttree=root->Left
2. if (Lefttree = Left - High) //case 1. Left of Left
1. rotateRight(root)
2. root->bal= even- high
3. Lefttree->bal =even- high
4. Taller=False
3 Else //Right of left case and double rotation
1 righttree= leftTree->Right
2. Adjust Balance factors
3. RotateLeft (Lefttree)
4. RotateRight (Root)
5. Taller=False
[End of if structure]
4. Return
5 End LeftBalance
AVL Delete
Algorithm AVLDelete
This algorithm deletes a node from an AVL tree
Pre:Root is pointer to a tree/subtree and
Delkey is the key of the node to be deleted.
Post: Node deleted if found, tree is unchanged if not
found. Shorter is true if subtree is shorter.
Return : pointer to root of new subtree
1. if (Tree=Null)
1. Shorter=false
2. Return null
2.endif
3. If (delkey<Root->key)
1. root->left = AVLDelete(Root->Left, deletekey,
shorter)
2. if (shorter)
1. root=DeleteRightBalance(Root,shorter)
3. endif
4 Else if (delkey > root->key)
1. root->right=AVLDelete (Root->right, deletekey, shorter)
2.if (shorter)
1. root= DeleteLeftBalance(root,shorter)
3. endif
5 Else
// delete node found—Test for leaf node
1. deleteNode=Root
2. if (No Left subtree)
1. Root=Root->Right
2. Shorter = true
3. Recycle (deleteNode)
4. Return success true
3. if (No Right subtree)
1. Root=Root->Left
2. Shorter = true
3. Recycle (deleteNode)
4. Return success true
4 else // deleted node has two subtrees
1. ExchPtr=Root->Left
2. Loop (ExchPtr->Right not Null)
1. ExchPtr=ExchPtr->Right
3. Root->Data=ExchPtr->Data
4.root->left= AVLDelete(Root->Left,ExchPtr-
>data, shorter)
5. if (shorter)
1. deleteRightBalance(Root,Shorter)
6. end if
5. End if
6. Return root
End AVLDelete
Variations of Balanced trees
Red Black tree
Motivation:
• Binary Search Trees should be balanced.
• AVL Trees need 2 passes: top-down insertion/deletion
and bottom-up rebalancing
Need recursive implementation
• Red-Black Trees need 1 pass: top-down rebalancing
and insertion/deletion
Can be implemented iteratively, faster
• Red-Black Trees have slightly weaker balance
restrictions
Less effort to maintain
In practice, worst case is similar to AVL Trees
Red black tree
• A red–black tree is a type of self-balancing binary search
tree
15 70
10 20 60 85
5 50 65 80 90
40 55
Splay Trees
• In balanced tree schemes, explicit rules are
followed to ensure balance.
• In splay trees, there are no such rules.
• Search, insert, and delete operations are like
in binary search trees, except at the end of
each operation a special step called splaying is
done.
• Splaying ensure that all operations take O(lg n)
Splay(78) 50
17 88
32 65 97
zig-zag
28 54 82
z
29 76
y
80
x
78
Splay(78) 50
17 88
32 65 97
zig-zag
28 54 82
x
29 78
z 76 y
80
Splay(78) 50
17 88
z
32 65 97
zig-zag
y
28 54 82
29 78 x
76 80
Splay(78) 50
17 88
32 x 78 97
zig-zag
28 z 65 y 82
29 54 76 80
17 88 y
32 x 78 97
zig-zag
28 65 82
29 54 76 80
17 50 z 88 y
82
32 97
zig-zag 65
80
28
54 76
29
17 50 88 w
82
32 97
zig 65
80
28
54 76
29
Splay(78)
17 50 88 w
82
32 97
zig 65
80
28
54 76
29