Sunteți pe pagina 1din 67

SFG

Sal F. Gamb
CS-342

C++ CS 342

Data Structures
&
Trees 1
SFG
Sal F. Gamb
Binary Trees CS-342

• A binary tree is an example of a NON-LINEAR structure.


This requires a more complex linking between the
components or NODES.
•A binary tree is a finite sets of nodes.
•Much of the terminology for trees comes from family
relations
•The following slide will show an example of a binary
tree and the terminology for trees.

2
Binary Trees SFG
LEFT
SUBTREE ROOT Sal F. Gamb
CS-342

M
LEAF
G P

A H N X

B I
LEAF
LEAF RIGHT
LEAF SUBTREE
3
Binary Trees SFG
LT CHILD of M
PARENT of A,H RT CHILD of Sal
M F. Gamb
PARENT of N,XCS-342
M

G P

A H N X

B I RT CHILD of G
PARENT of I

LT CHILD of G
PARENTof B
4
Binary Trees SFG
2 nodes with same Parent N & X are
Sal F. Gamb
A & H are sibling of G Descendent of P
CS-342

M
LEAF
G P

A H N X

B I H, G, M
are Ancestors
of I
LEAF and A LEAF and is
a Right Child of A NOT a Sibling of H
5
Depth of a node: Start at NODE N
Depth of
SFG
and move upward towards root
ROOT is 0 Sal F. Gamb
CS-342
1 2
M

Depth G 3 P 1
2
of
node
G is 1
A H 1 N X

Depth of
B I Depth of node X
node I is 2
is 3 6
Depth or Height of a Tree
SFG
Sal F. Gamb
CS-342

M 0

G P 1

A H N X 2

3
B I

Depth or Height of the Tree =7 3


A full binary tree with h levels
SFG
contains 2h -1 elements Sal F. Gamb
CS-342
Level 1 0 M
3 levels
1 G 2 P 23 -1
Level 2 8-1= 7
elements

3 A 4 H 5 N 6 X
Level 3
M G P A H N X
0 1 2 3 4 5 6
8
A COMPLETE binary tree BUT NOT FULL SFG
0 M Sal F. Gamb
CS-342
1 G 2 P

3 D 4 H 5 N 6 X

7 B 8 E

-1
M -1
G -1
P -1
D -1
H -1
N -1
X -1
B -1
E -1 -1

0 1 2 3 4 5 6 7 8 9 10
9
A Binary tree that is neither
SFG
COMPLETE nor FULL
Sal F. Gamb
M
CS-342

G P

A H N X

B I

-1
M -1
G -1
P A-1 -1
H -1
N -1
X -1 -1
B -1 -1
I
0 1 2 3 4 5 6 7 8 9 10

10
SFG
In-Order M
Sal F. Gamb
Traversal
CS-342
G P
Done!
visit Left
subtree
A H N visit Root
visit Right
B I subtree

A B G H I M N P
1. If tree is not COMPLETE add fake nodes Algorithm
2. Start at root & Trace the entire tree.
3. Mark node when visited
4. Write node when visited a SECOND time 11
SFG
In-Order 50
Sal F. Gamb
Traversal
CS-342
25 75
Done!
visit Left
12 subtree
33 67 88
visit Root
visit Right
6 13 68 subtree

6 12 13 25 33 50 67 68 75 88

12
SFG
Pre-Order M
Sal F. Gamb
Traversal
CS-342
G P
Done!
visit Root
visit Left
A H N Subree
visit Right
B I Subtree

M G A B H I P N

1. If tree is not COMPLETE add fake nodes Algorithm


2. Start at root & Trace the entire tree.
3. Write node when visited the FIRST time 13
SFG
Pre-Order 50
Sal F. Gamb
Traversal
CS-342
25 75
Done!
visit Root
12 33 visit Left
67 88
subtree
visit Right
6 13 68 subtree

50 25 12 6 13 33 75 67 68 88

14
SFG
Post-Order M
Sal F. Gamb
Traversal
CS-342
G P
Done!
visit Left
Subree
A H N visit Right
Subtree
B I visit Root

B A I H G N P M

1. If tree is not COMPLETE add fake nodes


Algorithm
2. Start at last node of left subtree. Trace the
left child, right child, and parent. (Repeat)
3. Write node when visited the FIRST time 15
SFG
Post-Order 50
Sal F. Gamb
Traversal
CS-342
25 75
Done!
visit Left
12 33 subtree
67 88
visit Right
subtree
6 13 68 visit Root

6 13 12 33 25 68 67 88 75 50

16
Summary of tree traversals SFG
Sal F. Gamb
CS-342
Position or Location of root :

Pre-Order
Beginning of output list
Traversal

In-Order
Traversal Middle of output list

Post-Order
End of output list
Traversal
17
SFG
Complete Binary Trees
Sal F. Gamb
Can be Implemented as: CS-342
•static arrays
•dynamic arrays (shrink & grow as needed)
•root is always at [ 0 ]
•To find the parent of node [ i ]------> [ (i - 1)/2 ]
(integer division)
•To find the Left Child of a node-----> [ 2i + 1 ]
•To find the Right Child of a node --> [ 2i + 2 ]

0
1 2
0 1 2 3 4 5 6
3 4 5 6
18
Complete Binary Trees SFG
PARENT Sal F. Gamb
0 CS-342
1 2
3 4 5 6 2 2 2
0 1 2 3 4 5 6

If i = 2 If i = 2 If i = 2
parent Left Child Right Child Left Child
= = =
[ ( i -1 )/2 ] [( 2i +1] [ ( 2i +2 ]
[ ( 2 -1 )/2] [( 2*2 +1)] [ ( 2*2 +2 )] Right Child
[ 1/2] [4 + 1] [ 4+2]
[0] [5] [6]

Int division 19
Complete Binary Trees SFG
PARENT Sal F. Gamb
0 CS-342
1 2
3 4 5 6 2 2 2
0 11 2 3 4 5 6

If i = 1 If i = 1 If i = 1
parent Left Child Right Child Right Child
= = =
[ ( i -1 )/2 ] [( 2i +1] [ ( 2i +2 ]
[ ( 1 -1 )/2] [( 2*1 +1)] [ ( 2*1 +2 )] Left Child
[ 0/2] [2 + 1] [ 2+2]
[0] [3] [4]

Int division 20
Complete Binary Trees SFG
Parent &
Sal F. Gamb
0 ROOT
CS-342
1 2
3 4 5 6 2 2 2
0 1 2 3 4 5 6

If i = 0 If i = 0 If i = 0 Right Child
parent Left Child Right Child
= = = Left Child
[ ( i -1 )/2 ] [( 2i +1] [ ( 2i +2 ]
[ ( 0 -1 )/2] [( 2*0 +1)] [ ( 2*0 +2 )]
[ -1/2] [0 + 1] [ 0+2]
[0] [1] [2]

Int division 21
Complete Binary Trees SFG
Sal F. Gamb
•We can store the tree as a fixed-sized array CS-342
by using the formulas
class requirements:
1) declare the array in private
2) declare a counter to keep track of
how much of the array is used
if dynamic
3) declare a var to keep track of the
complete size of the dynamic array
•also:
The formulas make it easy to traverse
the tree, when moving from node to node
22
Binary Search Trees SFG
Sal F. Gamb
CS-342
•How to build a BST
BST storage rules:
•RULE 1:
The entry in node n is greater than every
entry in its left sub-tree
(however it could be equal)
•RULE 2:
The entry in node n is less than every entry
in its right sub-tree

23
Binary Search Trees examples SFG
Sal F. Gamb
45, 53, 17, 9, 45, 53, 9,17, 3
CS-342
53, 3, 54 53, 3, 54 \
9
3, 9, 17,
Left Sub-Tree MORE \
45, 53,
LINEAR BALANCED 17
\ 53, 54
45 45 45
/ \ / \ \ BAD
17 53 9 53 53 ROOT
/ / \ / \ / \ \ Linear
9 53 54 3 17 53 54 53 linked list
/ \
3 54 24
Binary Search Trees insert an item SFG
Sal F. Gamb
45, 53, 9, 17, 53, 3, 54 CS-342

45 45 45 45
\ / \ / \
53 9 53 9 53
\
17

45 45 45
/ \ / \ /
\
9 53 9 53 9 53
\ / / \ / / \ / \
17 53 3 17 53 3 17 53 54 25
SFG
Sal F. Gamb
CS-342
TreeNode

LeftPtr data RightPtr

NULL 123 NULL

26
Declaring a Tree NODE class SFG
Any type of data Make Tree a friend
Sal F. Gamb
allows Tree to access
CS-342
this class
template<class NODETYPE>
(functions)
class TreeNode
{ constructor
friend class Tree<NODETYPE>;
public: Returns the data
TreeNode(const NODETYPE &); of the node
NODETYPE getData() const;
private: points to the left next node
TreeNode *leftPtr;
NODETYPE data; Data
TreeNode *rightPtr;
}; points to the right next node
27
SFG
Declaring a Tree NODE class
Sal F. Gamb
CS-342

template<class NODETYPE>
TreeNode<NODETYPE>::TreeNode(const NODETYPE &info)
{
leftPtr = 0;
data = info;
rightPtr = 0;
}
TreeNode
Constructor
leftPtr data rightPtr
initialiazes
NULL 123 NULL a node
28
SFG
Declaring a Tree NODE class
Sal F. Gamb
CS-342
template<class NODETYPE>
NODETYPE TreeNode<NODETYPE>::getData() const
{
return data;
}
Returns
a copy of the data
TreeNode in the node
leftPtr data rightPtr

NULL 123 NULL

29
Declaring A class Tree SFG
(friend of TreeNode) and
Sal F. Gamb
the rest of the FUNCTIONS
CS-342

•We need a class (Tree) that consists of all


functions needed to solve the problem
•a pointer that points to the ROOT
of the TreeNode class
•utility functions:
insert-Node-Helper, remove-Node-Helper
Pre-Order-Helper
In-Order-Helper, and
Post-Order-Helper
30
BST Class SFG
template<class NODETYPE>
Sal F. Gamb
class Tree
CS-342
{ public:
Tree();
void insertNode (const NODETYPE & );
void removeNode(const NODETYPE & );

void preOrderTraversal() const;


void inOrderTraversal() const;
void postOrderTraversal() const;

TreeNode<NODETYPE> * findMin
(TreeNode<NODETYPE> * ) const;
31
private: BST Class SFG
TreeNode<NODETYPE> * rootPtr; Sal F. Gamb
CS-342
void insertNodeHelper
(TreeNode<NODETYPE> **, const NODETYPE &);
void removeNodeHelper
(TreeNode<NODETYPE> *&, NODETYPE &);

void preOrderHelper
(TreeNode<NODETYPE> *) const;
void inOrderHelper
(TreeNode<NODETYPE> *) const;
void postOrderHelper
(TreeNode<NODETYPE> *) const;
}; 32
SFG
•Call this function from the MAIN driver
and pass the key to insert into BST Sal F. Gamb
•then, this function will call the insert CS-342

function to get the job done


RECURSIVELY

template<class NODETYPE>
void Tree<NODETYPE>::insertNode
(const NODETYPE &value)
{
insertNodeHelper(&rootPtr, value);
}

33
BST insert a node SFG
Sal F. Gamb
template<class NODETYPE> CS-342

void Tree<NODETYPE>::
insertNodeHelper (TreeNode<NODETYPE> **ptr,
const NODETYPE &value )
{
if ( *ptr == 0 ) // tree empty
{
*ptr = new TreeNode<NODETYPE>(value);
assert(*ptr != 0);
}
34
BST insert a node SFG
Sal F. Gamb
CS-342

else
if ( value < (*ptr)->data)
insertNodeHelper( & ( (*ptr)->leftPtr ), value );
else if ( value > (*ptr)->data)
insertNodeHelper( &( (*ptr)->rightPtr ),value);
else
cout << value << " dup " << endl;
}

35
SFG
BST Traversals:InOrder
Sal F. Gamb
CS-342

template<class NODETYPE>
void Tree<NODETYPE>::inOrderTraversal() const
{
if (rootPtr == NULL )
cout << "\n BST empty ...";
else
inOrderHelper(rootPtr);
}

36
SFG
BST Traversals:In-Order
Sal F. Gamb
CS-342

template<class NODETYPE>
void Tree<NODETYPE>::inOrderHelper
( TreeNode<NODETYPE> *ptr) const
{
if ( ptr != 0 )
{ inOrderHelper(ptr->leftPtr);
cout << ptr->data << ' ';
inOrderHelper(ptr->rightPtr);
}
}
37
SFG
BST Traversals:Pre-Order
Sal F. Gamb
CS-342

template<class NODETYPE>
void Tree<NODETYPE>::preOrderTraversal() const
{
if (rootPtr == NULL )
cout << "\n BST empty ...";
else
preOrderHelper(rootPtr);
}

38
SFG
BST Traversals:Pre-Order
Sal F. Gamb
CS-342

template<class NODETYPE>
void Tree<NODETYPE>::preOrderHelper
( TreeNode<NODETYPE> *ptr) const
{
if ( ptr != 0 )
{ cout << ptr->data << ' ';
preOrderHelper(ptr->leftPtr);
preOrderHelper(ptr->rightPtr);
}
}
39
SFG
BST Traversals:PostOrder
Sal F. Gamb
CS-342

template<class NODETYPE>
void Tree<NODETYPE>::postOrderTraversal() const
{
if (rootPtr == NULL )
cout << "\n BST empty ...";
else
postOrderHelper(rootPtr);
}

40
SFG
BST Traversals:Post-Order
Sal F. Gamb
CS-342

template<class NODETYPE>
void Tree<NODETYPE>::postOrderHelper
( TreeNode<NODETYPE> *ptr) const
{
if ( ptr != 0 )
{ postOrderHelper(ptr->leftPtr);
postOrderHelper(ptr->rightPtr);
cout << ptr->data << ' ';
}
}
41
Remove a node from a BST SFG
Sal F. Gamb
CS-342

CASE 1: delete a LEAF

•find the node


•check if node is a left or
right child
•set the parent to 0 or NULL

42
SFG
CASE 1: delete a leaf; node 3
Sal F. Gamb
CS-342
10 10

Par 5 15 5 15
0
3 8 8

ParLeftPtr
=
NULL
43
SFG
CASE 1: delete a leaf; node 8
Sal F. Gamb
CS-342

10 10

Par 5 15 Par 5 15
0

3 8 3

ParRightPtr
=
NULL
44
Remove a node from a BST SFG
Sal F. Gamb
CS-342

CASE 2: delete a node with one child

•find the node


•check if node is a left or right child
•the node can be removed after its
parent adjusts a pointer to bypass
the node

45
CASE 2a: delete 5 with a RT or LT child SFG
Sal F. Gamb
Par Par
10 10 CS-342

5 15 5 15

8 3

Par-->leftPtr Par-->leftPtr
= =
delPtr->rightPtr delPtr->leftPtr

46
CASE 2b: delete 15 with a RT or a LT child SFG
Sal F. Gamb
Par 10 Par 10 CS-342

5 15 5 15

3 13 23

Par-->rightPtr Par-->rightPtr
= =
delPtr->leftPtr delPtr->rightPtr

47
Remove a node from a BST SFG
Sal F. Gamb
CS-342
CASE 3: delete a node with Two Children
•Find the node
•Identify the right sub-tree
•Go right
•Find the smallest key of the right
sub-tree using a tempPtr
•Replace the key of the node to be
deleted with the smallest key of the
right sub-tree
•Adjust pointers & Delete tempPtr
48
Par SFG
12
Sal F. Gamb
CS-342
5 15

3 9

7 10

6 8

Find the node to be deleted


49
Par SFG
12
Sal F. Gamb
CS-342
5 15

3 9 Right
Sub-Tree
7 10

6 8

Identify the right sub-tree from that node


50
Par SFG
12
Sal F. Gamb
CS-342
5 15

3 9
Go right
7 10

6 8

Go right
51
Par SFG
12
Sal F. Gamb
CS-342
5 15

Go left 3 9 Right
Sub-Tree
7 10

6 8

Go left as far as you can go


52
Par SFG
12
Sal F. Gamb
CS-342
5 15

Go left 3 9 Right
Sub-Tree
7 10

6 8

Go left as far as you can go


53
Par SFG
12
Sal F. Gamb
CS-342
5 15

Smallest 3 9 Right
Key Sub-Tree
7 10

6 8

Replace 5 with 6
54
Par SFG
12
Sal F. Gamb
CS-342
6 15

Smallest 3 9 Right
Key Sub-Tree
7 10

6 8

Replace 5 with 6
55
Par SFG
12
Sal F. Gamb
CS-342
6 15

Smallest 3 9 Right
Key Sub-Tree
7 10

6 8

Adjust pointers & Delete TempPtr


56
SFG
12
Sal F. Gamb
CS-342
6 15

3 9

7 10

6 8

Done !
57
Remove a node from a BST SFG
Sal F. Gamb
•How to check if a node has CS-342
NO children
(LEAF)

LC DATA RC Ptr
0 300 0

If ( Ptr->LC == NULL && Ptr->RC == NULL )

58
Remove a node from a BST SFG
Sal F. Gamb
CS-342
•How to check if a node
has TWO children

LC DATA RC Ptr
300

If ( Ptr->LC != NULL && Ptr->RC != NULL )

59
Remove a node from a BST SFG
Sal F. Gamb
•How to check if a node CS-342
has ONE child
Right Child

LC DATA RC Ptr
0 300

If ( Ptr->LC == NULL && Ptr->RC != NULL )

60
Remove a node from a BST SFG
Sal F. Gamb
•How to check if a node CS-342
has ONE child
Left Child

LC DATA RC Ptr
300 0

If ( Ptr->LC != NULL && Ptr->RC == NULL )

61
• How to find the Function call: SFG
• smallest key of root=root->rightPtr
Sal F. Gamb
• the right Sub-Tree CS-342

template <class NODETYPE>


TreeNode<NODETYPE> * Tree<NODETYPE>::
findMin(TreeNode<NODETYPE> * ptr) const
{
if ( ptr == NULL )
return NULL;
else if ( ptr->leftPtr == NULL )
return ptr;
else
return findMin(ptr->leftPtr);
} 62
SFG
•Call this function from the MAIN driver
and pass the key to be deleted Sal F. Gamb
•then, this function will call the remove CS-342

function to get the job done


RECURSIVELY

template<class NODETYPE>
void Tree<NODETYPE>::
removeNode(const NODETYPE &value)
{
removeNodeHelper(rootPtr, value);
}
63
BST Remove function SFG
template<class NODETYPE> Sal F. Gamb
void Tree<NODETYPE>::removeNodeHelper CS-342

( TreeNode<NODETYPE> *&root, NODETYPE &value)


{
TreeNode<NODETYPE> *temp;
if ( root == NULL )
cout << "\n Element " << value << "not found";
else if (value < root->data)
removeNodeHelper( root->leftPtr, value);
else if (value > root->data)
removeNodeHelper( root->rightPtr, value);
64
SFG
node to be removed found
& Sal F. Gamb
has TWO Children CS-342

else if
(root->leftPtr != NULL && root->rightPtr != NULL)
{
temp = findMin(root->rightPtr);
root->data = temp->data;
removeNodeHelper(root->rightPtr, root->data);
}
65
SFG
The node has 1 child or none
Sal F. Gamb
else
CS-342
{ Only a RIGHT child
temp = root;
if (root->leftPtr == NULL )
root = root->rightPtr;
else if (root->rightPtr == NULL )
root=root->leftPtr;
delete temp; Only a LEFT child
}
}
66
SFG
BST summary
Sal F. Gamb

•Because of the recursive definition of BST CS-342


it is common to write the RECURSIVE functions
to implement BSTs
•the average depth of a BST is (log n)
running time:
•insert & search
•Best-case O( log n )
if tree is completely balanced
•Worst-case O( n )
if tree is linear
•Average-case ( log n )
67

S-ar putea să vă placă și