L8_Trees.pptx
L8_Trees.pptx
Dipannita Biswas
Md Mehrab Hossain Opi
1
Introduction
•A tree is a structure consisting of one node called the root and zero or
one or more subtrees.
• A tree has the following general properties:
1. One node is distinguished as a root;
2. Every node (excluding a root) is connected by a directed edge from exactly
one other node; A direction is: parent -> children
3. If a tree has N nodes then it will have (N-1) edges. There is only one path
from each node to any other node of the tree.
2
Types of tree
• Binary tree: Each parent node can have at most two children.
• Binary Search Tree: Given a binary tree, the left subtree of a node
contains only nodes with keys lesser than the node’s key and the right
subtree contains only nodes with keys greater than the node’s key.
• Full Binary Tree: every node has either zero or two children.
• Complete Binary Tree: all levels are filled, except for possibly the last
level, which is filled from left to right.
• Balanced Binary Tree: The heights of any node’s left and right
subtrees differ by at most one.
Basic Operations: Create, Insert, Delete, Traversal
3
Full Binary Tree
Binary Search Tree
5
Linked List Implementation
0X90 9 0X34
0X
01
0X86 6 NULL NULL 10 0X45
0X 0X
90 34
NULL 5 NULL NULL 11 NULL
0X86 0X45
9 6 10 5 Null Null 11
6
Traverse
• Preorder Traversal – visit root, left child, and then right child of a
subtree.
• Inorder Traversal – visit left child, root, and then right child of a
subtree.
• Postorder Traversal – visit left child, right child and then root of a
subtree.
7
Inorder(tree)
• Traverse the left subtree :
Inorder(left->subtree)
25
• Visit the root.
10 36 • Traverse the right subtree:
Inorder(right->subtree)
3 15
2 3 10 15 22 25 36
2 22
8
Preorder(tree)
• Visit the root.
25 • Traverse the left subtree:
Preorder(left->subtree)
10 36 • Traverse the right subtree:
Preorder(right->subtree)
3 15
25 10 3 2 15 22 36
2 22
9
Postorder(tree)
• Traverse the left subtree:
25 Postorder(left->subtree)
• Traverse the right subtree:
10 36 Postorder(right->subtree)
• Visit the root
3 15
2 3 22 15 10 36 25
2 22
10
Insert(node, data)
Insert 22
If node == NULL :
22<node
return createNode(data) 25
2 22
11
Delete(data)
• Case I
The node to be deleted is the leaf node. Simply delete the node from
the tree.
• Case II
The node to be deleted lies has a single child node.
1. Replace that node with its child node.
2. Remove the child node from its original position.
• Case III
The node to be deleted has two children.
1. Get the inorder successor of that node.
2. Replace the node with the inorder successor.
3. Remove the inorder successor from its original position.
12
25
10 36
Delete 3: NODE
with Single Child 32 15
13
25
Delete 10: NODE
with Both Children
10
12 36
3 15
2 12 22
14
The End
15