0% found this document useful (0 votes)
311 views

Tree Data Structure

The post-order traversal of the binary tree with pre-order traversal a b d e c f g and in-order traversal d b e a f c g is: e d c b a g f. In post-order traversal, nodes are visited after their left and right subtrees, so we process the leaf nodes first before interior nodes.

Uploaded by

Nahid Hasan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
311 views

Tree Data Structure

The post-order traversal of the binary tree with pre-order traversal a b d e c f g and in-order traversal d b e a f c g is: e d c b a g f. In post-order traversal, nodes are visited after their left and right subtrees, so we process the leaf nodes first before interior nodes.

Uploaded by

Nahid Hasan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Tree Data Structures

Why use a Tree?

Trees combines the advantages of two other data


structures an ordered array and a linked list.

You can search a tree quickly as you can an ordered


array.

You can also insert and delete items quickly as you


can with a linked list.
Tree Data Structures
A tree T is a set of nodes storing elements such that the nodes have
a parent-child relationship that satisfies the following:
if T is not empty, T has a special tree called the root that has no
parent
each node v of T different than the root has a unique parent node
w; each node with parent w is a child of w.

Recursive definition

T is either empty
or consists of a node r (the root) and a possibly empty set of trees
whose roots are the children of r
Trees Data Structures
Tree
Nodes
Each node can have 0 or more children
A node can have at most one parent
Binary tree
Tree with 02 children per node

Tree Binary Tree


Trees

Terminology
Root no parent
Leaf no child
Interior non-leaf
Height distance from root to leaf

Root node

Interior nodes Height

Leaf nodes
Tree Node Level and Path
Length

A L
evel:0

B C D L
evel:1

E F L
evel:2

G H L
evel:3

6
6 Min Index Contents
The level of a node is the length of the path from the root to that
node.

The Height of a tree is the maximum no of nodes in a branch of


the tree. This turns out to be 1 more than the largest level number
of tree, if we assign level 0 to root node.

The degree of a node is the number of partitions in the sub tree


which has that node as the root.

Nodes with degree=0 are called leaves


Depth vs Height

The depth is usually used to describe a property of a tree node, while


the height is used to describe the property of the entire tree, as in the
following examples:

Root node has a depth of zero.

The height of a tree is defined as the depth of its deepest node.

The ancestors of a node are all the nodes along the path from
the root to the node and Descendants after that nodes to leaves
node.
Tree Properties

Property Value
A Number of nodes
Height
B C Root Node
Leaves
D E F Interior nodes
Number of levels
Ancestors of H
G Descendants of B
Siblings of B
H I Right sub-tree of G
Representation of Trees

List Representation
( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) )
The root comes first, followed by a list of sub-trees

data link 1 link 2 ... link n

How many link fields are


needed in such a representation?
A Tree Node

Every tree node:


object useful information
children pointers to its children nodes

O O O

O
Left Child - Right Sibling

data
A
left child right sibling
B C D

E F G H I J

K L M
Tree Implementation

typedef struct tnode {


int key;
struct tnode* lchild;
struct tnode* sibling;
} *ptnode;

- Create a tree with three nodes (one root & two children)
- Insert a new node (in tree with root R, as a new child at level L)
- Delete a node (in tree with root R, the first child at level L)
[1] A
Sequential Representation [2] B
[3] C
[4] D
(1) waste space
A [1] A
[2] B (2) insertion/deletion [5] E
problem [6] F
[3] -- [7]
B G
[4] C [8]
A H
[5] -- [9]
C I
[6] --
[7] -- B C
D [8] D
[9] --
. . D E F G
E
[16] E

H I
Linked Representation
typedef struct tnode *ptnode;
typedef struct tnode {
int data;
ptnode left, right;
};

data
left data right

left right
Arithmetic Expression Using BT

+ inorder traversal
A/B*C*D+E
infix expression
* E
preorder traversal
+**/AB CDE
* D prefix expression
postorder traversal
AB/C *D*E+
/ C
postfix expression
level order traversal
A B +*E*D /CAB
Tree for Algebraic expression
+

* /

a b - e

c d

BINARYEXPRESSION TREEFOR "a*b + (c-d) / e"


17
17 Main Index Contents
Binary Tree
Full Binary Tree
Complete Binary Tree

The tree T is said to be complete if all its levels, except possibly


the last, have the maximum number of possible nodes.
Binary Tree Representations

If a complete binary tree with n nodes (depth =


log n + 1) is represented sequentially, then for
any node with index i, 1<=i<=n, we have:
parent(i) is at i/2 if i!=1. If i=1, i is at the root and
has no parent.
leftChild(i) is at 2i if 2i<=n. If 2i>n, then i has no
left child.
rightChild(i) is at 2i+1 if 2i +1 <=n. If 2i +1 >n,
then i has no right child.
A complete binary tree is very special tree, it provides the
best possible ratio between the number of nodes and the
height. The height h of a complete binary tree with N nodes
is at most O(log N). We can easily prove this by counting
nodes on each level, starting with the root, assuming that
each level has the maximum number of nodes:

n = 1 + 2 + 4 + ... + 2h-1 + 2h = 2h+1 - 1


Solving this with respect to h, we obtain

h = O(log n)
Advantages of trees:

Trees are so useful and frequently used, because they have


some very serious advantages:

Trees reflect structural relationships in the data


Trees are used to represent hierarchies
Trees provide an efficient insertion and searching
Trees are very flexible data, allowing to move sub-trees around
with minimum effort
Tree Traversal(recursive)
Preorder
Inorder
Postorder

Preorder:
Process the root
Traverse the left subtree in preorder
Traverse the right sub-tree in preorder

Inorder:
Traverse the left subtree in inorder
Process the root
Traverse the right sub-tree in inorder
Tree Traversal(recursive)
Postorder
Traverse the left subtree in postorder
Traverse the right sub-tree in postorder
Process the root
PreOrder Traversal
Inorder Traversal
Postorder Traversal
PreOrder Traversal

P(TreeNode)
Print (TreeNode.value)
If LeftPointer(TreeNode) != NULL
Then
P(TreeNode.LeftNode)
If RightPointer(TreeNode) != NULL
Then
P(TreeNode.RightNode)

F, B, A, D, C, E, G, I, H
Inorder Traversal

P(TreeNode)
If LeftPointer(TreeNode) != NULL
Then
P(TreeNode.LeftNode)
print(TreeNode.value)
If RightPointer(TreeNode) != NULL
Then
P(TreeNode.RightNode)

A, B, C, D, E, F, G, H, I
Postorder Traversal

P(TreeNode)
If LeftPointer(TreeNode) != NULL
Then
P(TreeNode.LeftNode)
If RightPointer(TreeNode) != NULL
Then
P(TreeNode.RightNode)
Print (TreeNode.value)

A, C, E, D, B, H, I, G, F
The in-order and pre-order traversal of a binary tree are:
d b e a f c g and a b d e c f g, respectively.
What will be the post-order traversal for the same tree?

First construct the tree:

a
/ \
b c
/\ / \
d e f g

Then traverse the tree in post order.


Q1. A binary tree T has 9 nodes. The inorder and preorder
traversal of T yields the following sequences of nodes:
Inorder: E A C K F H D B G
Preorder: F A E K C D H G B
Draw the tree for above.
Q1. A binary tree T has 9 nodes. The inorder and preorder traversal of T yields
the follwing sequences of nodes:
Postorder: E C K A H B G D F Preorder: F A E K C D H G B
Draw the tree for above.
In pre[], the leftmost element is root of tree. Here F is root.

The value next to F in pre[], must be left child of root. So, F is root and A
is left child. How to find the all nodes in left subtree?

We know A is root of all nodes in left subtree. All nodes before A in post[]
must be in left subtree. Now we know F is root, elements {E,C,K,A} are in
left subtree, and the elements {H,B,G,D} are in right subtree.

recursively follow the above approach and you will get the tree.
Postorder: E C K A H B G D F Preorder: F A E K C D H G B
F
/ \
(E C K A) (H,B,G,D) *postorder
First traverse left sub tree, here A will be root. Now decide left and right
sub-tree. Apply all the previous step, you can see in pre-order (A E K C D
H G B) A is root and E will left sub-tree and (C,K) will be right side.

F
/ \
A (H,B,G,D) *postorder
/ \

E (C,K)
F
/ \
A (H,B,G,D) *postorder
/ \
E (C,K) *postorder
Traverse right sub tree, here K will be root. Now decide left and right sub-tree.
Apply all the previous step, you can see in pre-order (K C D H G B) K is root and
C will left sub-tree. F
/ \
A (H,B,G,D) *postorder
/ \
E K *postorder
/
C
Same steps will be applied for right sub-tree. When no element is
remaining, you will find final tree.

F
/ \
A D
/\/ \
E K H G
/ /
C B
Arithmetic Expression Using BT

+ inorder traversal
A/B*C*D+E
infix expression
* E
preorder traversal
+**/AB CDE
* D prefix expression
postorder traversal
AB/C *D*E+
/ C
postfix expression
level order traversal
A B +*E*D /CAB
Inorder Traversal (recursive version)

void inorder(ptnode ptr)


/* inorder tree traversal */
{
if (ptr) { A/B*C*D+E
inorder(ptr->left);
printf(%d, ptr->data);
indorder(ptr->right);
}
}
Preorder Traversal (recursive version)

void preorder(ptnode ptr)


/* preorder tree traversal */
{
if (ptr) { +**/AB CDE
printf(%d, ptr->data);
preorder(ptr->left);
predorder(ptr->right);
}
}
Postorder Traversal (recursive version)

void postorder(ptnode ptr)


/* postorder tree traversal */
{
if (ptr) { AB/C * D * E+
postorder(ptr->left);
postdorder(ptr->right);
printf(%d, ptr->data);
}
}
Level Order Traversal
(using queue)

void levelOrder(ptnode ptr)


/* level order tree traversal */
{
int front = rear = 0;
ptnode queue[MAX_QUEUE_SIZE];
if (!ptr) return; /* empty queue */
enqueue(front, &rear, ptr);
for (;;) {
ptr = dequeue(&front, rear);
if (ptr) {
printf(%d, ptr->data);
if (ptr->left)
enqueue(front, &rear,
ptr->left);
if (ptr->right)
enqueue(front, &rear,
ptr->right);
}
else break;
} +*E*D /CAB
}
Euler Tour Traversal

generic traversal of a binary tree


the preorder, inorder, and postorder traversals are
special cases of the Euler tour traversal
walk around the
tree and visit each
node three times:
on the left
from below
on the right
Euler Tour Traversal (contd)

eulerTour(node v) {
perform action for visiting node on the left;
if v is internal then
eulerTour(v->left);
perform action for visiting node from below;
if v is internal then
eulerTour(v->right);
perform action for visiting node on the right;
}
Euler Tour Traversal (contd)

preorder traversal = Euler Tour with a visit only on


the left
inorder = ?
postorder = ?
Other applications: compute number of descendants
for each node v:
counter = 0
increment counter each time node is visited on the left
#descendants = counter when node is visited on the right
counter when node is visited on the left +
1
Running time for Euler Tour?
Application: Evaluation of
Expressions

+ inorder traversal
A/B*C*D+E
infix expression
* E
preorder traversal
+**/AB CDE
* D prefix expression
postorder traversal
AB/C *D*E+
/ C
postfix expression
level order traversal
A B +*E*D /CAB
Inorder Traversal (recursive version)

void inorder(ptnode ptr)


/* inorder tree traversal */
{
if (ptr) { A/B*C*D+E
inorder(ptr->left);
printf(%d, ptr->data);
inorder(ptr->right);
}
}
Preorder Traversal (recursive version)

void preorder(ptnode ptr)


/* preorder tree traversal */
{
if (ptr) { +**/AB CDE
printf(%d, ptr->data);
preorder(ptr->left);
preorder(ptr->right);
}
}
Postorder Traversal (recursive version)

void postorder(ptnode ptr)


/* postorder tree traversal */
{
if (ptr) { AB/C * D * E+
postorder(ptr->left);
postorder(ptr->right);
printf(%d, ptr->data);
}
}
Binary Search Trees

A Binary Search Tree is a binary tree with the following


properties:
All items in the left sub-tree are less than the root.
All items in the right sub-tree are greater or equal to the root.
Each sub-tree is itself a binary search tree.

Binary search trees provide an excellent structure for searching a


list and at the same time for inserting and deleting data into the
list.
7-2 BST Operations

We discuss four basic BST operations: traversal, search,


insert, and delete; and develop algorithms for searches,
insertion, and deletion.

Traversals
Searches
Insertion
Deletion

55
Three BST search algorithms:

Find the smallest node


Find the largest node
Find a requested node

56
57
58
59
60
61
62
BST Insertion

To insert data all we need to do is follow the


branches to an empty sub-tree and then insert
the new node.
In other words, all inserts take place at a leaf or
at a leaf like node a node that has only one null
sub-tree

63
64
65
30 30

30 30

66
Deletion

There are the following possible cases when we delete


a node:
The node to be deleted has no children. In this case, all
we need to do is delete the node.
The node to be deleted has only a right subtree. We
delete the node and attach the right subtree to the
deleted nodes parent.
The node to be deleted has only a left subtree. We
delete the node and attach the left subtree to the
deleted nodes parent.
The node to be deleted has two subtrees. It is possible
to delete a node from the middle of a tree, but the result
tends to create very unbalanced trees.

67
Deletion from the middle of a tree

Rather than simply delete the node, we try to


maintain the existing structure as much as
possible by finding data to take the place of
the deleted data. This can be done in one of
two ways.

68
Deletion from the middle of a tree

We can find the largest node in the deleted


nodes left sub tree and move its data to
replace the deleted nodes data.
We can find the smallest node on the deleted
nodes right sub tree and move its data to
replace the deleted nodes data.
Either of these moves preserves the integrity
of the binary search tree.

69
70
(continued)

71
27 27

27 27

72

You might also like