Você está na página 1de 67

PROBLEMS AND DIFFICULTIES

GIVE US THE CHANCE TO


BECOME STRONGER AND
BETTER.

TREES
Table of Contents
1) Introduction to Trees
Tree Terminology
Trees Properties
2) Binary Trees
Complete Binary Trees
Extended Binary Trees
3) Memory Representation
Sequential
Linked
4) Binary Tree Traversal
Pre-order
In-order
Post-order
5) Traversal Algorithms using Stacks

President-CEO

Production
Manager
Personnel
Manager
Purchasing
Supervisor

Warehouse
Supervisor

Sales
Manager

Shipping
Supervisor

HIERARC HIC AL TREE STRUC TURE

Definition of Tree
A tree is a finite set of one or more nodes
such that:
There is a specially designated node called
the root.
The remaining nodes are partitioned into n>=0
disjoint sets T1, ..., Tn, where each of these sets is
a tree.
We call T1, ..., Tn the subtrees of the root.

Tree Terminology

Terminology
The degree of a node is the number of subtrees
of the node
The degree of A is 3; the degree of C is 1.
The node with degree 0 is a leaf or terminal
node.
A node that has subtrees is the parent of the
roots of the subtrees.
The roots of these subtrees are the children of
the node.
Children of the same parent are siblings.
The ancestors of a node are all the nodes
along the path from the root to the node.

Store elements Hierarchically


The top element: root
Except the root, each element
has a parent
Each element has 0 or more
children

Ancestors of u

Descendants of u

Level Number
Each node in a binary tree T is assigned a Level
Number.
The root R of the tree T is assigned a level number 0.
Every other node is assigned a level number which is
one more than the level number of its parent.
The nodes with the same level number are said to
belong to the same generation.

Level: 0

A
B

C
E

D
F

Level: 1
Level: 2

Level: 3

Depth (or Height) of a Tree


The Depth (or Height ) of the tree T is the maximum
number of nodes in a branch of T.
The Height of a node in a tree is the length of a longest
path from a node to a leaf.
The Depth of a node is the length of the unique path
from the root to that node.
Height and Depth of a tree are symmetrical (equal), i.e.
Height of a tree is maximum depth of one of its leaves.
The depth of a node and the height of a node are not
necessarily equal.

Node B has height 3,


Node E has height 2,
Node K has height 1,

Node B has Depth 2


Node E has Depth 3
Node K has Depth 4

Exercise
Number of Nodes
Degree of a node(shown by green number)
Leaf node(terminal)
Non terminal nodes
Parent
Children
2
Sibling
Ancestor
2
0
Descendant
Level of a node
0
0
Height(depth) of a tree

Level
0
3
1

1
0

Exercise to do
A

Property
Number of nodes
Height
Root Node
Leaves
Interior nodes
Number of levels
Ancestors of H
Descendants of B
Siblings of E
Degree of node A

Value

Binary Trees

Binary Trees
A Binary Tree T is defined as a finite set of elements, called
nodes , such that:
a) T is empty (called null tree or empty tree) or
b) T contains a distinguished node R, called the root of T,
and the remaining nodes of T form an ordered pair of
disjoint binary tree T1(left subtree) and T2(right subtree).
[This definition of the binary tree is recursive. ]
Any node in Binary tree T has either 0,1 or 2 successors. i.e.
A special class of trees: max degree for each node is 2

Example
A
B
C

L
M

Left Subtree and Right Subtree ?


J

Difference between Binary tree and a General tree


A binary tree can be empty whereas a tree cannot be
empty.
Each element in binary tree has at most two sub trees
whereas each element in a tree can have any number of
sub trees
The sub trees of each element in a binary tree are
ordered. That is we can distinguish between left and
right sub trees. The sub trees in a tree are unordered.

Various Binary Trees


Skewed Binary Tree: If every node in a tree has only one child (except the Leaf
node), then we call such trees Skew Trees. If every node has only left child then we
call them as Left skew trees. Similarly, if every node has only right child then we
call them right skew trees.

C
D
Skewed 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, and if all the
nodes at the last level appear
as far left as possible.

Extended Binary Tree


A binary tree T is said to be a 2-tree or an extended binary tree if each node
N has either 0 or 2 children.
The nodes with 2 children are called internal nodes.
A

The nodes with 0 children are called external nodes.

A internal nodes are distinguished diagrammatically by using


The external and
circles for internal nodes and squares for external nodes.
B
B

C
D

F
G
G

Fig: Binary Tree T

Fig: Extended 2-tree

Maximum Number of Nodes in Binary Tree


The maximum number of nodes on level i of a
binary tree is 2i, i>=0.
The maximum number of nodes in a binary
tree of depth k is 2k-1, k>=1.

Full Binary Tree V/S Complete Binary Tree


A full binary tree of depth k is a binary tree of depth k
having 2k-1 nodes, k>=0.
A binary tree with n nodes and depth k is
complete iff its nodes correspond to the nodes numbered
from 1 to n in the full binary tree of depth k.
A

A
B
D
H

E
I

C
F

Complete binary tree

D
I

G
M

Full binary tree of depth 4

Complete Binary Tree


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.

Representing Binary Trees in Memory


Binary trees are represented using two ways:
Sequential Representation (using Single Array)
Linked Representation (using Linked Lists)

[ The main Requirement of any representation of T is that one should have


direct access to the root R of T and given any node N of T, one should have
direct access to the children of N. ]

Sequential Representation
This representation uses only a single linear array TREE as
follows:
The root R of T is stored in TREE[1].
If a node N occupies TREE[K], then its left child is
stored in TREE[2*K] and its right child is stored in
TREE[2*K+1].
oNULL is used to indicate an empty sub tree.
oIn particular, TREE[1]=NULL indicates that the tree is
empty.

Advantages of Sequential Representation


1. No need to store left and right pointers in the nodes
2. Direct access to nodes: to get to node k, access A[k]
TREE
1 45

45

2 22
3 77
4 11
5 30
6
7 90

22

77

9 15
10 25
11
12

11

30

90

13
14 88
15
16
.
.

15

25

88

.
29

save memory

It can be seen that a sequential representation of a binary


tree requires numbering of nodes; starting with nodes on
level 1, then on level 2 and so on. The nodes are
numbered from left to right .
It is an ideal case for representation of a complete binary
tree and in this case no space is wasted. However for
other binary trees, most of the space remains unutilized.
As can be seen in the figure, we require 14 locations in
array even though the tree has only 9 nodes. If null entries
for successors of the terminal nodes are included, we
would actually require 29 locations instead of 14.Thus
sequential representation is usually inefficient unless
binary tree is complete or nearly complete

[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]

Sequential Representation is usually inefficient unless, the Binary tree


T is complete or nearly complete.

[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
.
[16]

(1) waste space


(2) insertion/deletion
problem

A
B
-C
----

B
D
-.
E

A
B
C
D
E
F
G
H
I

Linked Representation
Tree T will be maintained in memory by means of a linked
Representation which uses three parallel arrays, INFO,
LEFT and RIGHT, and a pointer variable ROOT.

1. INFO[K] contains the data at the node N


2. LEFT[K] contains the location of the left child of
the node N
3. RIGHT[K] contains the location of the right child
of node N.
Data

[Where K is the location ]

left

right

Linked Representation
Pointer variable ROOT contains the location of
the root R of T.
If the tree T ids empty, then ROOT will contain
the null value.
If any subtree of the tree is empty, then the
corresponding pointer will contain the null
value.
left

data

right

Exercise
Construct a Binary tree using Linked Representation
Root

INFO

LEFT

RIGHT

14

Avail

10

17

18

13

19

10

11
12

13

12

14

15

15

16

16

11

17

18

19

20

20

Binary Tree Traversals


There are three standard ways of traversing a
binary tree T with root R.
These three algorithms, called:
Preorder
Inorder
Postorder

Preorder
1. Process the root R.
2. Traverse the left subtree of R in preorder.
3. Traverse the right subtree of R in preorder.
Inorder
1. Traverse the left subtree of R in inorder.
2. Process the root R.
3. Traverse the right subtree of R in inorder.
Postorder
1. Traverse the left subtree of R in postorder.
2. Traverse the right subtree of R in postoder.
3. Process the root R.

Preorder
a
b

c
a b c

1. Process the root R.


2. Traverse the left subtree of R in preorder.
3. Traverse the right subtree of R in preorder.

Preorder Example
a
b

c
e

d
g

a b d g h e i

c f

Preorder of Expression Tree


/

*
e
+
a

* + a b -

c d + e

Gives prefix form of expression !

Inorder Example
a
b

c
b a c

1. Traverse the left subtree of R in inorder.


2. Process the root R.
3. Traverse the right subtree of R in inorder.

Inorder Example
a
b

c
e

d
g

g d h b e i

a f

Inorder of Expression Tree


/

*
e
+
a

d /

Gives Infix form of expression !

Postorder Example
a
b

c
b c a

1. Traverse the left subtree of R in postorder.


2. Traverse the right subtree of R in postoder.
3. Process the root R.

Postorder Example
a
b

c
e

d
g

g h d i

e b j

c a

Postorder of Expression Tree


/

*
e
+
a

a b + c d -

* e f

Gives postfix form of expression!

Illustrations for Traversals


1

Assume: visiting a node


3

is printing its label


Preorder:
1 3 5 4 6 7 8 9 10 11 12
Inorder:
4 5 6 3 1 8 7 9 11 10 12
Postorder:
4 6 5 3 8 11 12 10 9 7 1

5
4

9
10

6
11

12

Illustrations for Traversals (Contd.)


Assume: visiting a node
15

is printing its data


Preorder: 15 8 2 6 3 7
Inorder: 2 3 6 7 8 10 11
Postorder: 3 7 6 2 10 14
12 11 8 22 30 27 20 15

6 10 12
3

27

11

11 10 12 14 20 27 22 30
12 14 15 20 22 27 30

20

22
14

30

Arithmetic Expression Using Binary Tree


+

preorder traversal
+**/ABCDE
prefix expression
inorder traversal
A/B*C*D+E
infix expression
postorder traversal
AB/C*D*E+
postfix expression

Some Examples
a

preorder = ab

b
inorder = ab

b
b

a
postorder = ab

b
b

a
level order = ab

a
a

a
b

Binary Tree Construction


Can you construct the binary tree, given
two traversal sequences?
Depends on which two sequences are
given.

Construct a Binary Tree from given


Inorder and Preorder Sequence
Inorder Sequence : D B E A F C
Preorder Sequence : A B D E C F

Problem: Create a tree from the given traversals


preorder: F A E K C D H G B
inorder: E A C K F H D B G
Solution: The tree is drawn from the root as follows:
(a) The root of tree is obtained by choosing the first node of
preorder. Thus F is the root of the proposed tree
(b) The left child of the tree is obtained as follows:
(a) Use the inorder traversal to find the nodes to the left and right of the
root node selected from preorder. All nodes to the left of root node(in
this case F) in inorder form the left subtree of the root(in this case E A
CK)
(b) All nodes to the right of root node (in this case F ) in inorder form the
right subtree of the root (H D B G)
(c) Follow the above procedure again to find the subsequent roots and
their subtrees on left and right.

F is the root Nodes on left subtree( left of F):E A C K (from inorder)


Nodes on right subtree(right of F):H D B G(from inorder)
The root of left subtree:
From preorder: A E K C , Thus the root of left subtree is A
D H G B , Thus the root of right subtree is D
Creating left subtree first:
From inorder: elements of left subtree of A are: E (root of left)
elements of right subtree of A are: C K (root of right)
Thus tree till now is:
F
A
E

D
K

As K is to the left of C in preorder

Creating the right subtree of F


The root node is D
From Inorder, the nodes on the left of D are: H (left root of D)
the nodes on the right of D are: B G (right root of D)
Thus the tree is:
F

Inorder And Preorder


inorder = g d h b e i a f j c
preorder = a b d g h e i c f j
Scan the preorder left to right using the inorder to
separate left and right subtrees.
a is the root of the tree; gdhbei are in the left
subtree; fjc are in the right subtree.
a
gdhbei

fjc

Inorder and Preorder


a
gdhbei

fjc

Preorder = a b d g h e i c f j
b is the next root; gdh are in the left
subtree; ei are in the right subtree.
a

b
gdh

fjc
ei

Inorder And Preorder


a
b
gdh

fjc
ei

preorder = a b d g h e i c f j
d is the next root; g is in the left subtree;
h is in the right subtree.
a
fjc

b
d
g

ei
h

Inorder And Postorder

Scan postorder from right to left using inorder to


separate left and right subtrees.

inorder = g d h b e i a f j c
postorder = g h d i e b j f c a
Tree root is a; gdhbei are in left subtree; fjc are in
right subtree.

Preorder Traversal (using stack)


Algorithm 9: PREORD(INFO, LEFT, RIGHT, ROOT)
The algorithm does a preorder traversal of Binary tree T, applying an operation PROCESS to
each of its nodes. An array STACK is used to temporarily hold the addresses of nodes.
1. Set TOP:= 1, STACK[1]:= NULL and PTR := ROOT.
2. Repeat Steps 3 to 5 while PTR != NULL:
3. Apply PROCESS to INFO[PTR].
4. [Right Child?]
If RIGHT[PTR]!= NULL then
Set TOP := TOP+1, and STACK[TOP]:= RIGHT[PTR].
[end of If structure]
5. [Left Child?]
If LEFT[PTR]!= NULL then
Set PTR:= LEFT[PTR].
Else
Set PTR:= STACK[TOP] TOP:= TOP-1.
[End of If structure]
[End of step 2 Loop]
6. Exit.

Preorder Traversal Algorithm


This is simulation of above algorithm showing contents of stack
1. Initially push NULL onto the STACK:
STACK =
Then set PTR :=A, the root of T.
2. Proceed down the left most path rooted at PTR = A as
follows:
(i) Process A and push its right child C onto Stack:
STACK: , C
(ii) Process B (There is no Right Child)
(iii) Process D and push its right child H onto STACK:
STACK: , C, H
(iv) Process G (There is no Right Child)
No other node is processed, since G has no left child.
3. [Backtracking] Pop the top Element H from STACK, and Set
PTR = H. This leaves STACK: , C
Since PTR NULL, return to step (a) of the algorithm.
4. Proceed down to the left-most path rooted at PTR= H as
follows:
(v) Process H and push its right child K onto STACK:
STACK: , C, K
5.[Backtracking] Pop K from STACK, and set PTR:= K. This
leaves :
STACK: , C

E
H
k

Preorder Traversal Algorithm (Ctd.)

6. Proceed down the left most path rooted at PTR= K as follows:


(vi) Process K. (There is no right child)
No other node is processed, since K has no left child.
7. [Backtracking] Pop C from Stack, and set PTR := C. This leaves:
STACK:
Since PTR NULL, return to Step (a) of the algorithm.
8. Proceed down the left most path rooted at PTR = C as follows:
(vii) Process C and push its right child F onto STACK:
STACK: , F
(viii) Process E. (There is no right child)
9. [Backtracking] Pop F from STACK, and set PTR :=F, This leaves
STACK:
10. Proceed down the left-most path rooted at PTR :=F as follows:
(ix)Process F.
No other node is processed, since F has no left child.
11. [Backtracking] Pop the top element NULL from STACK, and set PTR:=
NULL.
Since PTR=NULL, the algorithm is completed.
As seen from the steps 2, 4, 6, 8 and 10, the nodes are processed in order A,
B, D, G, H, K, C, E, F. This is required preorder traversal.

Inorder Traversal (using stack)


Algorithm 9: INORD(INFO, LEFT, RIGHT, ROOT)
The algorithm does a inorder traversal of Binary tree T, applying an operation PROCESS to
each of its nodes. An array STACK is used to temporarily hold the addresses of nodes.
1. Set TOP:= 1, STACK[1]:= NULL and PTR := ROOT.
2. Repeat while PTR != NULL:
a) Set TOP:=TOP+1, STACK[TOP]:=PTR.
b) Set PTR:= LEFT[PTR].
[End of loop]
3. Set PTR:=STACK[TOP], TOP:=TOP-1.
4. Repeat Steps 5 to 7 while PTR != NULL:
5. Apply PROCESS to INFO[PTR].
6. If RIGHT[PTR]!= NULL, then:
a) Set PTR:=RIGHT[PTR]
b) Go to Step 2.
[End of If structure]
7. Set PTR:=STACK[TOP] and TOP:=TOP-1.
[End of step 4 Loop.]
8. Exit

Postorder Traversal (using stack)


Algorithm 9: POSTORD(INFO, LEFT, RIGHT, ROOT)
The algorithm does a postorder traversal of Binary tree T, applying an operation PROCESS to
each of its nodes. An array STACK is used to temporarily hold the addresses of nodes.
1.
2.
3.
4.

Set TOP:= 1, STACK[1]:= NULL and PTR := ROOT.


Repeat Step 3 to 5 while PTR!=NULL:
Set TOP := TOP+1, STACK[Top]:=PTR.
If RIGHT[PTR]!=NULL, then:
Set TOP := TOP+1, Stack[Top]:=-RIGHT[PTR].
[End of If structure]
5. Set PTR:=LEFT[PTR]
[End of step 3 Loop]
6. Set PTR:=STACK[Top], TOP := TOP-1.
7. Repeat while PTR>0:
a)Apply PROCESS to INFO[PTR].
b)PTR:=STACK[Top], TOP := TOP-1.
[End of Loop]
8. If PTR<0, then:
a) Set PTR:= -PTR.
b) Go to Step 2.
[End of If structure]
9. Exit.

Similar and Copy Tree


E

C
Tree T1

G
Tree T2

D
Tree T3

Tree T4

1) Tree T1,T2 and T3 is said as Similar Tree because Structure of these


trees is same.
2) Tree T1 and T3 is said as Copy Tree because along with structure ,
content(data) part of both trees are same.
3) Tree T1 and Tree T4 are neither similar nor Copy tree.

Exercise
Q1: The post order traversal of a binary tree is 452631. Find out the pre
order traversal
a. 126345
b. 142653
c. 124536
d. 124356
Q2: The inorder and preorder traversals of a binary tree are d h b e f c I g j
and a b d h e c f g I j respectively. The Post order traversal is
a) h d e b f i j g c a
b) d h e b i j g f c a
c) e h d b f i j g c a
D) h e d b f i j g a c