0% found this document useful (0 votes)
81 views76 pages

Trees

This document discusses trees as a data structure. It defines key tree terminology like root, parent, child, leaf, and subtree nodes. It also covers different types of trees like binary trees and their properties. Binary tree traversal methods like preorder, inorder, and postorder are explained along with examples to demonstrate how each traversal visits the nodes. Calculations for the number of nodes and depth/height of a binary tree are presented as well.

Uploaded by

esha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views76 pages

Trees

This document discusses trees as a data structure. It defines key tree terminology like root, parent, child, leaf, and subtree nodes. It also covers different types of trees like binary trees and their properties. Binary tree traversal methods like preorder, inorder, and postorder are explained along with examples to demonstrate how each traversal visits the nodes. Calculations for the number of nodes and depth/height of a binary tree are presented as well.

Uploaded by

esha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 76

Lecture 09: Trees Data Structures

Trees
Lecture 09: Trees Data Structures

Trees
Lecture 09: Trees Data Structures

Parts of a Tree
Hierarchical data structure
Each position in the tree is called a node
nodes
Lecture 09: Trees Data Structures

Parts of a Tree
•The “top” of the tree is called the root or Parent node
Parent/Root
node
Lecture 09: Trees Data Structures

Parts of a Tree
The nodes immediately below a node are called its children

parent child
node nodes

5
Lecture 09: Trees Data Structures

Parts of a Tree

parent child
node nodes
Lecture 09: Trees Data Structures

Parts of a Tree
nodes with no children are called leaves (or terminal nodes), or terminal nodes

leaf
root node
nodes
Lecture 09: Trees Data Structures

Trees: Basic terminology[1]


• A node x is ancestor of node y if x is father of y or father of some ancestor
of y.

• y is called descendent of x. Ancestor of a node is its parent, grand parent or


grand-grand parent or so on….

y C
Lecture 09: Trees Data Structures

Trees Traversal

Nodes with the same parent are siblings


B and C are siblings A

B C
Lecture 09: Trees Data Structures

Parts of a Tree
A node plus the collection of nodes beneath it is called a subtree

sub-tree

10
Lecture 09: Trees Data Structures

Parts of a Tree
A node plus the collection of nodes beneath it is called a subtree

sub-tree
Lecture 09: Trees Data Structures

Depth/Height of A Node
The number of nodes in the longest path from the root to a leaf
is the depth (or height) of the tree

nodes Depth 0

Depth 1

Depth 2

Depth 3
Lecture 09: Trees Data Structures

Depth/Height of A Node
The number of nodes in the longest path from the root to a leaf
is the depth (or height) of the tree

nodes Height 3

Height 2

Height 1

Height 0
Lecture 09: Trees Data Structures

Binary Trees

• A commonly used type of tree is a binary tree


• Each node has at most two children
• The “tree” is a conceptual structure
• The data can be stored either in a dynamic linked tree
structure, or in contiguous memory cells (array)
according to a set pattern; in other words,
implementation can be pointer-based or array-based
Lecture 09: Trees Data Structures

Binary Tree
A commonly used type of tree is a binary tree
Each node has at most two children

nodes
Lecture 09: Trees Data Structures

Full Binary Tree


Every leaf has the same depth, and every non-
leaf has two children

nodes
Lecture 09: Trees Data Structures

Complete Binary Tree


All the depths are full, except the deepest,
where the nodes are as far left as possible
nodes
Lecture 09: Trees Data Structures

Binary trees
• A tree is called strictly binary tree if every non leaf node has exactly two
children.
• A strictly binary tree having n leaves always contain 2n-1 nodes
• Text book definition of depth of a tree
– Depth of binary tree is maximum level of any leaf in the tree.
– Root of tree is at level 0, and level of any other node in the tree is one more than
the level of its father
Lecture 09: Trees Data Structures

Calculating Number of Nodes


Lecture 09: Trees Data Structures

Binary Trees

• A complete binary tree of level d is the strictly binary tree all of whose
leaves are at level d
• A complete binary tree of level d has 2l nodes at each level l where
0<=l<=d
• Total number of nodes (tn) in a complete binary tree of depth d will
be:

d
tn  2 0  21  2 2      2 d   2 j  2 d 1  1
j 0

For a binary tree of height h there are O(2h) nodes


Lecture 09: Trees Data Structures

Binary Trees
• For a complete binary tree if number of nodes (tn) are known, then we may
find depth of the binary tree

d 1
tn  2 1
d 1
2  tn  1
d  1  log 2 (tn  1)
 d  log 2 (tn  1) - 1
A binary tree with nodes n has height O(log2n)
Lecture 09: Trees Data Structures

Traversal
• Systematic way of visiting all the nodes.

• Methods:
– Preorder, Inorder, and Postorder

• They all traverse the left subtree before the right subtree.

• The name of the traversal method depends on when the node


is visited.
Lecture 09: Trees Data Structures

Trees Traversal

• Inorder
Root
– (Left) Root (Right)
• Preorder
– Root (Left) (Right) Left Right
• Postorder
– (Left) (Right) Root
Lecture 09: Trees Data Structures

Pre-Order Traversal

• Visit the node.

• Traverse the left subtree.

• Traverse the right subtree.


Lecture 09: Trees Data Structures

Preorder Traversal
Root Left Right manner
• + Left Right +

• + [*Left Right] [+Left Right]


* +
• +(*AB) [+ *Left Right E]
• +*AB + *C D E
A B * E

C D
Lecture 09: Trees Data Structures

Example: Pre-Order

43

31 64

20 40 56 89

28 33 47 59

43 31 20 28 40 33 64 56 47 59 89
Lecture 09: Trees Data Structures

In-Order Traversal

• Traverse the left subtree.

• Visit the node.

• Traverse the right subtree.


Lecture 09: Trees Data Structures

Inorder Traversal
Left Root Right manner
+

• Left + Right
* +
• [Left*Right]+[Left+Right]
• (A*B)+[(Left*Right)+E) A B * E
• (A*B)+[(C*D)+E]
C D

(A*B)+(C*D+E)
Lecture 09: Trees Data Structures

Example: In-Order

43

31 64

20 40 56 89

28 33 47 59

20 28 31 33 40 43 47 56 59 64 89
Lecture 09: Trees Data Structures

Post-Order Traersal

• Traverse the left subtree.

• Traverse the right subtree.

• Visit the node.


Lecture 09: Trees Data Structures

Postorder Traversal
Left Right Root manner
+

• Left Right +
* +
• [Left Right *] [Left Right+] +
• (AB*) [Left Right * E + ]+ A B * E
• (AB*) [C D * E + ]+
• AB* C D * E + +
C D
Lecture 09: Trees Data Structures

Example: Post-Order

43

31 64

20 40 56 89

28 33 47 59

28 20 33 40 31 47 59 56 89 64 43
Lecture 09: Trees Data Structures

Binary Trees Storage


• Linked List based implementation
• Array based implementation
Lecture 09: Trees Data Structures

Binary Tree: Array


• Value in root node stored first, followed by left child, then right child

• Each successive level in the tree stored left to right; unused nodes in tree
represented by a bit pattern to indicate nothing stored there

• Children of any given node n is stored in cells 2n and 2n + 1 (If array index
starts at 1)

• Can calculate position for any given node

• Storage allocated as for full tree, even if many nodes empty

• For a tree of depth h we need array of 2h+1-1 cells


Lecture 09: Trees Data Structures

Array Representation
• Arrays are very easily used to represent complete binary trees
• Example

L G

O R I T

H M S
Lecture 09: Trees Data Structures

Array Representation
1

2
3

4 5
6 7

8 9 10 11 12 13

Parent(i) Left(i) Right(i)


return i/2 return 2i return 2i + 1
Lecture 09: Trees Data Structures

Advantages of using Array Representation


• Root always appear at array[0]

• Suppose non-root node at location array[i], then the data


for its parents is always at location array[(i-1)/2]

• Similarly data for its children is always at the following


location
– Left child at array[2i+1]
– Right child at array[2i+2]

• These formulas make it easy to implement algorithms


that traverse the tree
Lecture 09: Trees Data Structures

Disadvantages of using Array Representation

• The sequential representation of a tree with depth d will


require an array with approximately 2d+1 elements.

• So this sequential representation is usually inefficient


unless the binary tree is complete or nearly complete.
Lecture 09: Trees Data Structures

Binary Tree: as a linked structure

• Each node in the tree consists of:


– The data, or value contained in the element
– A left child pointer (pointer to first child)
– A right child pointer (pointer to second child)
Lecture 09: Trees Data Structures

Binary Tree: as a linked structure


• A root pointer points to the root node
– Follow pointers to find every other element in the tree
• Add and remove nodes by manipulating pointers
• Leaf nodes have child pointers set to null
Lecture 09: Trees Data Structures

class CBinTree
{
struct Node
{
int value;
Node *LeftChild,*RightChild;
}*Root;
/***Operations*********/
/************************/
};
Lecture 09: Trees Data Structures

ROOT
Lecture 09: Trees Data Structures

Binary Trees

• Full binary tree of height (depth) h: all nodes at a


height less than h have exactly two children
• Balanced binary tree: for each node, the difference in
depth of the right and left subtrees is no more than
one
• Completely balanced tree: left and right subtrees of
every node have the same height
Lecture 09: Trees Data Structures

Primitive Operations
• Left(node): Gives index/pointer of left child
• Right(node): Gives index/pointer of right child
• Parent(node): Returns index/pointer of parent
• Brother(node): Returns index/pointer of brother
• Root: Gives index/pointer of root node
• Info(Node): Data/Info stored at node
• IsLeft(node): Is node left child? Yes/No
• IsRight(node): Is node right child? Yes/No
Lecture 09: Trees Data Structures

Binary Search Tree


• Elements are sorted:
• For any node n in a binary search tree:
– The value at n is greater than the values of any of the nodes in its left
subtree
– The value at n is less than the values of any of the nodes in its right subtree
– Its left and right subtrees are binary search trees
• Need to define “greater than” and “less than” for the specific data
Lecture 09: Trees Data Structures

Expression Trees
• Expression tree for:
(a+b*c) +((d*e+f)*g)

•Inorder traversal
•Preorder traversal
•Postorder traversal
Lecture 09: Trees Data Structures

Binary Search Tree


• For every node, X, in the tree, the values of all the keys in its
left subtree are smaller than the key value of X, and the values
of all the keys in its right subtree are larger than the key value
of X.

X

Lecture 09: Trees Data Structures
Binary Search Tree Operations

There are many operations one can perform on a binary search tree.

a) Creating a binary search tree


b) Inserting a node into a binary search tree
c) Finding a node in a binary search tree
d) Deleting a node in a binary search tree.

We will use a simple class that implements a binary tree to store


integer values.

Creating a Binary Tree

We create an IntBinaryTree class.


Lecture 09: Trees Data Structures

The basic node of our binary tree has the following struct declaration.

struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
}

The class IntBinaryTree declaration is -


IntBinaryTree.h
class IntBinaryTree
{
private:
struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
};
Lecture 09: Trees Data Structures
TreeNode *root;
void destroySubTree(TreeNode *);
void deleteNode(int, TreeNode *&);
void makeDeletion(TreeNode *&);
void displayInOrder(TreeNode *);
void displayPreOrder(TreeNode *);
void displayPostOrder(TreeNode *);
public:
IntBinaryTree() // Constructor
{ root = NULL; }
~IntBinaryTree() // Destructor
{ destroySubTree(root); }
void insertNode(int);
bool searchNode(int);
void remove(int);
void showNodesInOrder(void)
{ displayInOrder(root); }
void showNodesPreOrder()
{ displayPreOrder(root); }
void showNodesPostOrder()
{ displayPostOrder(root); }
};
Lecture 09: Trees Data Structures

The root pointer is the pointer to the binary tree. This is similar
to the head pointer in a linked list.

The root pointer will point to the first node in the tree, or to NULL
(if the tree is empty).

It is initialized in the constructor.

The destructor calls destroySubTree, a private member function,


that recursively deletes all the nodes in the tree.

Inserting a Node

The code to insert a new value in the tree is fairly straightforward.

First, a new node is allocated, and its value member is initialized


with the new value.
Lecture 09: Trees Data Structures
Note, we assume that our binary tree will store no duplicate values.

void IntBinaryTree::insertNode(int num)


{
TreeNode *newNode, // Pointer to a new node
*nodePtr; // Pointer to traverse the tree

// Create a new node


newNode = new TreeNode;
newNode->value = num;
newNode->left = newNode->right = NULL;

if (!root) // Is the tree empty?


root = newNode;
else
{
nodePtr = root;
Lecture 09: Trees Data Structures
while (nodePtr != NULL)
{ if (num < nodePtr->value)
{ if (nodePtr->left)
nodePtr = nodePtr->left;
else
{ nodePtr->left = newNode;
break;
}
}
else if (num > nodePtr->value)
{ if (nodePtr->right)
nodePtr = nodePtr->right;
else
{ nodePtr->right = newNode;
break;
}
}
else
{ cout << "Duplicate value found in tree.\n";
break;
}
}
}
}
Lecture 09: Trees Data Structures
Program

// This program builds a binary tree with 5 nodes.

#include <iostream.h>
#include "IntBinaryTree.h“

void main(void)
{
IntBinaryTree tree;

cout << "Inserting nodes. ";


tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
cout << "Done.\n";
}
Lecture 09: Trees Data Structures
Program

Figure shows the structure of the binary tree built by the program.

Note: The shape of the tree is


determined by the order in
which the values are inserted.
The root node in the diagram
above holds the value 5 because
that was the first value inserted.
Lecture 09: Trees Data Structures
The IntBinaryTree class can display all the values in the tree using
all 3 of these algorithms.

The algorithms are initiated by the following inline public member


functions -

void showNodesInOrder(void)
{ displayInOrder(root); }
void showNodesPreOrder()
{ displayPreOrder(root); }
void showNodesPostOrder()
{ displayPostOrder(root); }

Each of these public member functions calls a recursive private


member function, and passes the root pointer as argument.

The code for these recursive functions is simple -


Lecture 09: Trees Data Structures
void IntBinaryTree::displayInOrder(TreeNode *nodePtr)
{
if (nodePtr)
{
displayInOrder(nodePtr->left);
cout << nodePtr->value << endl;
displayInOrder(nodePtr->right);
}
}

void IntBinaryTree::displayPreOrder(TreeNode *nodePtr)


{
if (nodePtr)
{
cout << nodePtr->value << endl;
displayPreOrder(nodePtr->left);
displayPreOrder(nodePtr->right);
}
}
Lecture 09: Trees Data Structures
void IntBinaryTree::displayPostOrder(TreeNode *nodePtr)
{
if (nodePtr)
{
displayPostOrder(nodePtr->left);
displayPostOrder(nodePtr->right);
cout << nodePtr->value << endl;
}
}
Lecture 09: Trees Data Structures

Program

// This program builds a binary tree with 5 nodes.


// The nodes are displayed with inorder, preorder,
// and postorder algorithms.
#include <iostream.h>
#include "IntBinaryTree.h“

void main(void)
{
IntBinaryTree tree;

cout << "Inserting nodes.\n";


tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
Lecture 09: Trees Data Structures
cout << "Inorder traversal:\n";
tree.showNodesInOrder();
cout << "\nPreorder traversal:\n";
tree.showNodesPreOrder();
cout << "\nPostorder traversal:\n";
tree.showNodesPostOrder();
}

Program Output
 
Inserting nodes.
Inorder traversal:
3
5
8
9
12
 
Lecture 09: Trees Data Structures
Preorder traversal:
5
3
8
12
9

Postorder traversal:
3
9
12
8
5

As an intellectual exercise, convince yourself that for each of the 3


algorithms, the 3 output orders of the values of the 3 traversals are
correct.
Lecture 09: Trees Data Structures

Searching the Tree


The IntBinaryTree class has a public member function called
searchNode, that returns true if a value is found in the tree, or
false otherwise.

The function starts at the root node, and traverses the tree, until it
finds the search value, or runs out of nodes.
bool IntBinaryTree::searchNode(int num)
{
TreeNode *nodePtr = root;

while (nodePtr)
{
if (nodePtr->value == num)
return true;
else if (num < nodePtr->value)
nodePtr = nodePtr->left;
else
nodePtr = nodePtr->right;
}
return false;
}
Lecture 09: Trees Data Structures

Program

// This program builds a binary tree with 5 nodes.


// The SearchNode function determines if the
// value 3 is in the tree.
#include <iostream.h>
#include "IntBinaryTree.h“

void main(void)
{
IntBinaryTree tree;

cout << "Inserting nodes.\n";


tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
Lecture 09: Trees Data Structures
if (tree.searchNode(3))
cout << "3 is found in the tree.\n";
else
cout << "3 was not found in the tree.\n";
}

Program Output
 
Inserting nodes.
3 is found in the tree.

Deleting a Node

To delete a leaf node is easy -


a) Find its parent
b) Set the child pointer that links to it to NULL
c) Free the node’s memory
Lecture 09: Trees Data Structures
How to delete a node if it has child nodes?

We want to delete the node, but preserve the sub-trees, that the
node links to.

There are 2 possible situations to be faced when deleting a non leaf


node -

1) The node has one child.


2) The node has two children.
Lecture 09: Trees Data Structures

The problem is not as easily solved if the node has two children.
Lecture 09: Trees Data Structures

We cannot attach both of the node’s subtrees to its parent.

One solution is to -
a) find a position in the right subtree to attach the left subtree.
b) attach the node’s right subtree to the parent
Lecture 09: Trees Data Structures

Now the code - to delete a node from the IntBinaryTree, call the
public member remove. The argument passed to the function is the
value of the node you want to delete.
Lecture 09: Trees Data Structures

void IntBinaryTree::remove(int num)


{
deleteNode(num, root);
}
The remove member function calls the deleteNode member
function. It passes the value of the node to delete, and the root
pointer.
The deleteNode member function is shown below -
Lecture 09: Trees Data Structures
void IntBinaryTree::deleteNode(int num, TreeNode *&nodePtr)
{
if (num < nodePtr->value)
deleteNode(num, nodePtr->left);
else if (num > nodePtr->value)
deleteNode(num, nodePtr->right);
else
makeDeletion(nodePtr);
}

Notice the declaration of the nodePtr parameter:


TreeNode *&nodePtr;
nodePtr is not simply a pointer to a TreeNode structure, but a reference to a
pointer to a TreeNode structure. Any action performed on nodePtr is actually
performed on the argument passed into nodePtr

The reason for doing this is explained shortly.

The deleteNode function uses an if/else statement.


Lecture 09: Trees Data Structures
if(num < nodePtr->value)
deleteNode(num, nodePtr->left);

The above statement compares the parameter num with the value
member of the node that nodePtr point to.

If num is less, the value being searched for will appear somewhere
in the nodePtr’s left subtree (if it appears at all).

So recall the deleteNode function recursively, with num as the first


argument, and nodePtr->left as the second argument.

If num is not less than nodePtr->value, the the following else if


statement is executed.

else if(num > nodePtr->value)


deleteNode(num, nodePtr->right);
Lecture 09: Trees Data Structures

If num is greater than nodePtr->value, then the value being searched


for will appear somewhere in nodePtr’s right subtree (if it appears
in the tree at all).

If num is equal to nodePtr->value, then neither of the if statements


above will find a true condition.

So, nodePtr points to the node to be deleted, and the trailing else will
be executed.

else
makeDeletion(nodePtr);

The makeDeletion function actually deletes the node from the tree
and reattaches the deleted node’s sub trees.
Lecture 09: Trees Data Structures
It must have access to the actual pointer in the tree to the node that
is being deleted (not just a copy of the pointer).

This is why the nodePtr parameter in the deleteNode function is a


reference. It must pass to makeDeletion, the actual pointer, to the
node to be deleted.

void IntBinaryTree::makeDeletion(TreeNode *&nodePtr)


{
TreeNode *tempNodePtr; // Temporary pointer, used in
// reattaching the left subtree.

if (nodePtr == NULL)
cout << "Cannot delete empty node.\n";
else if (nodePtr->right == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->left; // Reattach the left child
delete tempNodePtr;
}
Lecture 09: Trees Data Structures
else if (nodePtr->left == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->right; // Reattach the right child
delete tempNodePtr;
}
// If the node has two children.
else
{
// Move one node the right.
tempNodePtr = nodePtr->right;
// Go to the end left node.
while (tempNodePtr->left)
tempNodePtr = tempNodePtr->left;
// Reattach the left subtree.
tempNodePtr->left = nodePtr->left;
tempNodePtr = nodePtr;
// Reattach the right subtree.
nodePtr = nodePtr->right;
delete tempNodePtr;
}
}
Lecture 09: Trees Data Structures
Program

// This program builds a binary tree with 5 nodes.


// The DeleteNode function is used to remove two
// of them.
#include <iostream.h>
#include "IntBinaryTree.h“

void main(void)
{
IntBinaryTree tree;

cout << "Inserting nodes.\n";


tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);

cout << "Here are the values in the tree:\n";


tree.showNodesInOrder();
Lecture 09: Trees Data Structures

cout << "Deleting 8...\n";


tree.remove(8);
cout << "Deleting 12...\n";
tree.remove(12);

cout << "Now, here are the nodes:\n";


tree.showNodesInOrder();
}

Program Output
Inserting nodes.
Here are the values in the tree:
3
5
8
9
12
Deleting 8...
Deleting 12...
Now, here are the nodes:
3
5
9

You might also like