You are on page 1of 43

Data Structures and Algorithms

Binary Trees
Sidra Malik
sidra.malik@ciitlahore.edu.pk
Binary Tree
Binary Trees
• The simplest form of tree is a Binary Tree
• A Binary Tree consists of
– T which is empty
– A node (called the root node) and
– Disjoint Left and right subtrees , T1 and T2
– Both the subtrees are themselves binary trees
• Note: this is a recursive definition
• (A node can’t have more than 2 children)

Binary tree General tree

DS&A--Sidra Malik 3
Binary Trees…
Difference b/w Trees and Binary Trees

• A Tree can never be empty but a binary tree may be


empty.
• Binary Tree can’t have more than 2 children whereas in
case of a tree a node may have any number of children

Binary tree General tree

DS&A--Sidra Malik 4
Binary Tree
• A binary tree is either empty or has the
following form:

root

TL TR

• Where Tleft and Tright are binary trees.


DS&A--Sidra Malik 5
Binary Trees
• Full binary tree: is said to be full if it contains
maximum possible number of nodes in all
levels

• Complete binary tree: is said to be complete if


it contains maximum possible number of
nodes except possibly the last level

DS&A--Sidra Malik 6
Binary Trees

DS&A--Sidra Malik 7
Binary Trees
• Skewed binary tree: Contains only left or right
children.
• Similar: Two trees with same structure and
different data.
• Copy or identical: Same structure and same
data.

DS&A--Sidra Malik 8
Properties of Binary Trees
• Max number of nodes on level l is 2l , l >= 0

• If h = height of a binary tree, max number of


nodes possible are = 2h - 1

• Minimum number of nodes possible in


binary Tree are h
Binary tree

• For any non empty binary Tree, if n is number


of nodes and e are edges then
n=e+1
• A binary tree with height h and 2h - 1 nodes is
called a full binary tree

DS&A--Sidra Malik 9
Binary Tree Structure
• The representation of a binary tree structure is
relatively straightforward.
• We need a variable to store the data at the node
and 2 pointers to the left and right subtrees.

struct Node {
int data
Node *left
Node *right
}

DS&A--Sidra Malik 10
Binary Tree Structure

DS&A--Sidra Malik 11
Binary Tree Operations
• Insertion
– Into empty or existing Tree
• Deletion
– From a non empty Tree
• Traversal
– To visit all nodes in Binary Tree
• Merge
– To merge two binary trees into a larger one

DS&A--Sidra Malik 12
Visiting and Traversing a Node
• Many applications require that all of the
nodes of a tree be “visited”.
• Visiting a node may mean printing contents,
retrieving information, making a calculation,
etc.
• Traverse: To visit all the nodes in a tree in a
systematic fashion.
– A traversal can pass through a node without
visiting it at that moment.

DS&A--Sidra Malik 13
Depth First and Breadth First Traversal
• Depth-first traversals: using the top-down
view of the tree structure. Traverse the root,
the left subtree and the right subtree.
• Breadth-first or level-order traversal: visit
nodes in order of increasing depth. For nodes
of same depth visit in left-to-right order.

DS&A--Sidra Malik 14
Traversal strategies
• Preorder traversal
• Work at a node is performed before its children are
processed.
• Postorder traversal
• Work at a node is performed after its children are
processed.
• Inorder traversal
• For each node:
– First left child is processed, then the work at the node is
performed, and then the right child is processed.

DS&A--Sidra Malik 15
Tree Traversal Types

DS&A--Sidra Malik 16
Preorder Traversal

Preorder = root node


Preorder
of each subtree before
the subsequent left
and right subtrees.
subtrees.

DS&A--Sidra Malik 17
Inorder Traversal
• In the inorder traversal, the left subtree is
processed first, followed by the root node, and
then the right subtree.

Inorder = root node in between


the left and right subtrees.

DS&A--Sidra Malik 18
Inorder Traversal

DS&A--Sidra Malik 19
Inorder Traversal
• Application: draw a binary tree or Arithmetic
expression printing

((2 × (a − 1)) + (3 × b))


DS&A--Sidra Malik 20
Example of Binary Tree (inorder)

DS&A--Sidra Malik 21
Postorder Traversal
• In the postorder traversal, the left subtree is
processed first, followed by the right subtree,
and then the root node.

Postorder = root node after


the left and right subtrees.

DS&A--Sidra Malik 22
Postorder Traversal
Postorder Traversal

DS&A--Sidra Malik 23
Postorder Traversal

• In a postorder traversal, a node is visited after


its descendants
• Application: compute space used by files in a
directory and its subdirectories

DS&A--Sidra Malik 24
BINARY SEARCH TREES

DS&A--Sidra Malik 25
Binary Search Tree
• A binary search(sorted) tree is a binary tree storing keys (or
key-element pairs) satisfying the following property:
– Let u, v, and w be three nodes such that u is in the left
subtree of v and w is in the right subtree of v. We have
• key(u) <= key(v) <= key(w)

DS&A--Sidra Malik 26
Binary Search Tree
Property
• given a node with a value X, all the values of nodes in the left
subtree are smaller than X and all the values of the nodes in
the right subtree are larger than X

DS&A--Sidra Malik 27
Binary Search Tree Operations
• Create Tree - initialize a new tree
• isEmpty - return true if empty, false if not
• search - return pointer to node in whichkey is found,
otherwise return NULL
• findMin - return smallest node value
• findMax - return largest node value
• insert - insert a new node into the tree maintaining BST
property. All inserts are done at a leaf
• remove - remove a node from the tree maintaining BST
property.
• display - print a tree in an order traversal

DS&A--Sidra Malik 28
Array Implementation of BST
A BST can be implemented with an array
Given a node i
• parent(i) = (i - 1)/2
– If i = 0, then no parent since root
• leftChild(i) = 2i+1
– If 2i+1 <= N, otherwise no child
• rightChild(i) = 2i+2
– If 2i+2 <= N, otherwise no child

DS&A--Sidra Malik 29
Array Implementation of BST

DS&A--Sidra Malik 30
Array Implementation of BST
• Array Implementation?

DS&A--Sidra Malik 31
Array vs. Linked List Implementation
• Array disadvantages
– Wasted space
– Not enough space
• Linked implementation
– Similar to linked list -size can grow and shrink
easily during runtime

DS&A--Sidra Malik 32
Searching in BST
• To search for a key k, we trace a downward path starting at
the root
• The next node visited depends on the outcome of the
comparison of k with the key of the current node
• If we reach a leaf, the key is not found and we return null
– Example: find(4)

DS&A--Sidra Malik 33
Searching in BST
• Recursive Implementation
Node* search ( Node*nodePtr,itemtype key )
if (nodePtr == NULL)
return NULL
else if ( nodePtr->item == key )
return nodePtr
else if ( nodePtr->item > key )
return search(nodePtr->left, key)
else
return search(nodePtr->right, key)

DS&A--Sidra Malik 34
Deletion in BST
• Traverse tree and search for node to remove
• Five possible situations
– Item not found
– Removing a leaf
– Removing a node with one child - right only
– Removing a node with one child - left only
– Removing a node with two children

DS&A--Sidra Malik 35
Deletion…
Removing a Leaf

DS&A--Sidra Malik 36
Deletion…
Removing nodes with children
• Otherwise the node has children – find
replacement node
– If the left child exists
• Replace node information with the largest value smaller
than the value to remove
• findMax(leftChild)
– Else there is a right child
• Replace node information with the smallest value larger
than value to remove
• findMin(rightChild)

DS&A--Sidra Malik 37
Deletion…
Removing nodes with children
• Splice out replacement node (call remove
recursively)
• Just copy in info of replacement node over the
value to remove (overload = if necessary)
– Note - this is NOT the best solution if you have a
large data structure. The overhead of the copy is
too great and you should move the node instead.
• Delete replacement node if leaf

DS&A--Sidra Malik 38
Deletion…
Removing nodes with children

DS&A--Sidra Malik 39
Deletion…
Removing nodes with children

DS&A--Sidra Malik 40
Deletion…
Removing nodes with children

DS&A--Sidra Malik 41
Expression Trees
+

+ ×

a × + g

b c × f

d e

Expression tree for ( a + b × c) + ((d ×e + f) × g)

There are three notations for a mathematical expression:


1) Infix notation : ( a + (b × c)) + (((d ×e) + f) × c)
2) Postfix notation: a b c × + d e × f + g * +
3) Prefix notation : + + a × b c × + × d e f g
DS&A--Sidra Malik 42
Expression Tree traversals
• Depending on how we traverse the expression tree,
we can produce one of these notations for the
expression represented by the three.
• Inorder traversal produces infix notation.
» This is a overly parenthesized notation.
» Print out the operator, then print put the left subtree inside
parentheses, and then print out the right subtree inside
parentheses.
• Postorder traversal produces postfix notation.
» Print out the left subtree, then print out the right subtree, and then
printout the operator.
• Preorder traversal produces prefix notation.
» Print out the operator, then print out the right subtree, and then
print out the left subtree.

DS&A--Sidra Malik 43

You might also like