09 Binary Trees
09 Binary Trees
b c
d e f
g h i j k
5
l
Left ≠ Right
The following two binary trees are different:
A A
B B
In the first binary tree, node A has a left child but no right child; in the
second, node A has a right child but no left child
Put another way: Left and right are not relative terms
6
More terminology
Node A is the parent of node B if node B is a child of A
Node A is an ancestor of node B if A is a parent of B, or if
some child of A is an ancestor of B
In less formal terms, A is an ancestor of B if B is a child of A, or
a child of a child of A, or a child of a child of a child of A, etc.
Node B is a descendant of A if A is an ancestor of B
Nodes A and B are siblings if they have the same parent
Binary Trees T and T` are said to be similar if they have
the sa,e structure or, in other words they have same
shape.
The trees are said to be copies if they are similar and if
7 they have the same content at corresponding nodes.
Size and depth
The size of a binary tree is the
a number of nodes in it
This tree has size 12
b c The depth of a node is its distance
from the root
d e f a is at depth zero
e is at depth 2
g h i j k The depth of a binary tree is the
depth of its deepest node
l This tree has depth 4
8
Complete Tree
A tree T is said to be complete if all its
levels except possibly the last , have the
maximum number if possible nodes, and all
nodes at last level appear as far left as
possible.
A complete tree ensures:
optimum utilization of memory space
Keeps depth of tree in check
Keeps tree balance
Reduces the average search time.
A complete tree with all leaf nodes are at
the same level becomes a Full Tree
9
Extended binary tree or 2-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.
In such a case, the nodes with 2 children are called internal nodes,
and the nodes with 0 children are called external nodes
Sometimes the nodes are distinguished in diagrams by using circles
for internal nodes and squares for external nodes.
The term extended comes form following operation:
Sometimes a binary tree is converted to a 2-tree by replacing each empty
subtree by a new node.
Nodes of the original tree become internal nodes and added nodes or
extended nodes become external nodes.
A 2-tree is ideal for implementations like algebric expressions.
10
Balance
a a
b c b
c e
d e f g
d f
h i j
g h
A balanced binary tree
i j
An unbalanced binary tree
A binary tree is balanced if every level above the lowest is “full” (contains
2n nodes)
In most applications, a reasonably balanced binary tree is desirable
11
Representation of Binary trees in memory
12
Linked representation of Tree
Tree T will be maintained in memory by means of linked
representation which uses structure objects containing two
pointers of tree type, apart from storing data, to hold address
of left and right successor.
Formation will be :
Struct Tree
{
int data;
Tree *left, *right;
}root;
13
Sequential representation of Tree
In this method we can store pointers/references of tree
nodes using an array in memory called as sequential
representation such that:
The root of T is stored in TREE[k]
Left child of root is stored in Tree[2*k]
Right child of root is stored in Tree[2*k+1]
Same rule is followed on every sub tree
This formation is ideally suited for complete tree or full trees
to avoid any unnecessary wastage of memory space.
14
binary search trees
A binary tree is sorted if every node in the tree is larger than
(or equal to) its left descendants, and smaller than (or equal
to) its right descendants
Equal nodes can go either on the left or the right (but it has
to be consistent)
10
8 15
4 12 20
15 17
Binary search in a sorted array
Look at array location (lo + hi)/2
Searching for 5:
(0+6)/2 = 3
Using a binary
hi = 2;
(0 + 2)/2 = 1 lo = 2; search tree
(2+2)/2=2
7
3 13
0 1 2 3 4 5 6
2 3 5 7 11 13 17 2 5 11 17
16
Tree traversals
A binary tree is defined recursively: it consists of a root, a left
subtree, and a right subtree
To traverse (or walk) the binary tree is to visit each node in the
binary tree exactly once
Tree traversals are naturally recursive
Since a binary tree has three “parts,” there are three main ways to
traverse the binary tree:
Pre-order (root, left, right)
In-order (left, root, right)
Post-order (left, right, root)
17
class BinaryTree
class BinaryTree<V> {
V value;
BinaryTree<V> leftChild;
BinaryTree<V> rightChild;
// Assorted methods…
}
A constructor for a binary tree should have three parameters,
corresponding to the three fields
An “empty” binary tree is just a value of null
18
Preorder traversal (recursive)
In preorder, the root is visited first, followed by left child and right
child.
Here’s a preorder traversal to print out all the elements in the
binary tree:
19
Pre-order (non-recursive)
Initially push NULL onto STACK and then set PTR:=ROOT.
Then repeat the following steps while PTR!=NULL
1. Proceed down the left most path rooted at PTR, processing
each node N on the path and pushing each right child
R(N), if any, onto STACK. The traversing ends after a node
N with no left child L(N) is processed. PTR is updated like
PTR:=PTR(left)
2. [Backtracking] Pop and assign to PTR the top element on
STACK. If PTR!=NULL, then return to previous step.
Otherwise exit.
20
Inorder traversal (recursive)
In inorder, the root is visited in the middle. Every tree’s left child is
visited, then root, then right child
Here’s an inorder traversal to print out all the elements in the
binary tree:
21
Inorder traversal (non recursive)
Initially push NULL onto STACK and then set PTR:=ROOT.
Then repeat the following steps while PTR!=NULL
1. Proceed down the left most path rooted at PTR, pushing
each node N onto STACK and stopping when a node with
no left child is pushed on stack.
2. [Backtracking] Pop and process the nodes on STACK. If
NULL is popped then exit. If node N with a right child
R(N) is processed, set PTR=R(N) then return to previous
step.
22
Postorder traversal ( recursive )
In postorder, the root is visited last. Sequence startw with visiting left
node, then root node then right node.
Here’s a postorder traversal to print out all the elements in the
binary tree:
23
Postorder traversal (non recursive)
Initially push NULL onto STACK and then set PTR:=ROOT.
Then repeat the following steps while PTR!=NULL
1. Proceed down the left most path rooted at PTR, At each
node N of the path, push N onto STACK, and if N has a
right child R(N), push –R(N) pushed on stack.
2. [Backtracking] Pop and process positive nodes on STACK.
If NULL is popped then exit. If a negative node is popped,
i.e. if PTR=-N for some node N, set PTR=N and return to
step 1
24
Tree traversals using “flags”
The order in which the nodes are visited during a tree traversal
can be easily determined by imagining there is a “flag” attached to
each node, as follows:
A A A
B C B C B C
D E F G D E F G D E F G
25
ABDECFG DBEAFCG DEBFGCA
Other traversals
The other traversals are the reverse of these three standard ones
That is, the right subtree is traversed before the left subtree is
traversed
Reverse preorder: root, right subtree, left subtree
Reverse inorder: right subtree, root, left subtree
Reverse postorder: right subtree, left subtree, root
26
Finding a Node
To find a node given its key value, start from the root.
If the key value is same as the node, then node is found.
If key is greater than node, search the right subtree, else
search the left subtree.
Continue till the node is found or the entire tree is traversed.
Time required to find a node depends on how many levels
down it is situated, i.e. O(log N).
Search a value
t=root;
Flag=0;
while(t!=NULL)
{ if( t->data == value)
{ flag=1; break; }
else if( value < t->data)
t=t->left;
else
t=t->right;
}
if(flag==1)
printf("\nElement found");
else
printf("\nElement not found");
28
Inserting a Node
To insert a node we must first find the place to insert it.
Follow the path from the root to the appropriate node, which
will be the parent of the new node.
When this parent is found, the new node is connected as its
left or right child, depending on whether the new node’s key
is less or greater than that of the parent.
Inserting a new node (recursive)
Void insert(Tree *root, Tree *newnode)
{
if( newnode->data < root->data)
{
if(root->left==NULL)
root->left=newnode;
else
insert(root->left,newnode);
}
else
{
if(root->right==NULL)
root->right=newnode;
else
Insert( root->right, newnode);
}
}
30
Finding Maximum and Minimum Values
For the minimum,
go to the left child of the root and keep going to the left child
until you come to a leaf node. This node is the minimum.
For the maximum,
go to the right child of the root and keep going to the right
child until you come to a leaf node. This node is the maximum.
Deleting a Node
Start by finding the node you want to delete.
Then there are three cases to consider:
1. The node to be deleted is a leaf
2. The node to be deleted has one child
3. The node to be deleted has two children
Deletion cases: Leaf Node
To delete a leaf node, simply change the appropriate child
field in the node’s parent to point to null, instead of to the
node.
The node still exists, but is no longer a part of the tree.
So we can comfortably delete the node.
Deletion: One Child
The node to be deleted in this case has only two connections:
to its parent and to its only child.
Connect the child of the node to the node’s parent, thus
cutting off the connection between the node and its child,
and between the node and its parent.
Deletion: Two Children
Deletion: Two Children
To delete a node with two children, replace the node with its
inorder successor.
For each node, the node with the next-highest key (to the deleted
node) in the subtree is called its inorder successor.
To find the successor,
start with the original (deleted) node’s right child.
Then go to this node’s left child and then to its left child and so on, following
down the path of left children.
The last left child in this path is the successor of the original node.
Find successor
Delete a node with subtree (case 1)
Delete a node with subtree (case 2)
Delete a node with subtree (case 3)
Expression Tree
43
A Binary Expression Tree is . . .
‘*’
‘-’ ‘/’
‘4’ ‘2’
45
Levels Indicate Precedence
46
A Binary Expression Tree
‘*’
‘+’ ‘3’
‘4’ ‘2’
( 4 + 2 ) * 3 = 18
47
Easy to generate the infix, prefix, postfix expressions
‘*’
‘-’ ‘/’
‘4’ ‘2’
Infix: ((8-5)*((4+2)/3))
Prefix: *-85 /+423
Postfix: 85- 42+3/*
48
Inorder Traversal: (A + H) / (M - Y)
Print second
tree
‘/’
‘+’ ‘-’
‘A’ ‘H ‘Y
’ ‘M’ ’
Print first
tree
‘/’
‘+’ ‘-’
‘A’ ‘H ‘Y
’ ‘M’ ’
Print last
tree
‘/’
‘+’ ‘-’
‘A’ ‘H ‘Y
’ ‘M’ ’