Tree Data Structure Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Tree Data Structure

A tree is a kind of data structure that is used to represent the data in hierarchical form. It can
be defined as a collection of objects or entities called as nodes that are linked together to
simulate a hierarchy. Tree is a non-linear data structure as the data in a tree is not stored linearly
or sequentially.

A tree is also one of the data structures that represent hierarchical data. Suppose we want to
show the employees and their positions in the hierarchical form then it can be represented as
shown below:

The above tree shows the organization hierarchy of some company. In the above
structure, john is the CEO of the company, and John has two direct reports named
as Steve and Rohan. Steve has three direct reports named Lee, Bob, Ella where Steve is a
manager. Bob has two direct reports named Sal and Emma. Emma has two direct reports
named Tom and Raj. Tom has one direct report named Bill. This particular logical structure is
known as a Tree. Its structure is similar to the real tree, so it is named a Tree. In this structure,
the root is at the top, and its branches are moving in a downward direction. Therefore, we can
say that the Tree data structure is an efficient way of storing the data in a hierarchical way.Skip
10s

Let's understand some key points of the Tree data structure.

© Dr. Ganesh Khekare


o A tree data structure is defined as a collection of objects or entities known as nodes that
are linked together to represent or simulate hierarchy.
o A tree data structure is a non-linear data structure because it does not store in a
sequential manner. It is a hierarchical structure as elements in a Tree are arranged in
multiple levels.
o In the Tree data structure, the topmost node is known as a root node. Each node
contains some data, and data can be of any type. In the above tree structure, the node
contains the name of the employee, so the type of data would be a string.
o Each node contains some data and the link or reference of other nodes that can be called
children.

Some basic terms used in Tree data structure.

Let's consider the tree structure, which is shown below:

In the above structure, each node is labeled with some number. Each arrow shown in the above
figure is known as a link/edge between the two nodes.

o Root: The root node is the topmost node in the tree hierarchy. In other words, the root
node is the one that doesn't have any parent. In the above structure, node numbered 1

© Dr. Ganesh Khekare


is the root node of the tree. If a node is directly linked to some other node, it would
be called a parent-child relationship.
o Child node: If the node is a descendant of any node, then the node is known as a child
node.
o Parent: If the node contains any sub-node, then that node is said to be the parent of that
sub-node.
o Sibling: The nodes that have the same parent are known as siblings.
o Leaf Node:- The node of the tree, which doesn't have any child node, is called a leaf
node. A leaf node is the bottom-most node of the tree. There can be any number of leaf
nodes present in a general tree. Leaf nodes can also be called external nodes.
o Internal nodes: A node has atleast one child node known as an internal.
o Ancestor node:- An ancestor of a node is any predecessor node on a path from the
root to that node. The root node doesn't have any ancestors. In the tree shown in the
above image, nodes 1, 2, and 5 are the ancestors of node 10.
o Descendant: The immediate successor of the given node is known as a descendant of
a node. In the above figure, 10 is the descendant of node 5.

Properties of Tree data structure

o Recursive data structure: The tree is also known as a recursive data structure. A tree
can be defined as recursively because the distinguished node in a tree data structure is
known as a root node. The root node of the tree contains a link to all the roots of its
subtrees. The left subtree is shown in the yellow color in the below figure, and the right
subtree is shown in the red color. The left subtree can be further split into subtrees
shown in three different colors. Recursion means reducing something in a self-
similar manner. So, this recursive property of the tree data structure is implemented

© Dr. Ganesh Khekare


in various applications.

o Number of edges: If there are n nodes, then there would n-1 edges. Each arrow in the
structure represents the link or path. Each node, except the root node, will have atleast
one incoming link known as an edge. There would be one link for the parent-child
relationship.
o Depth of node x: The depth of node x can be defined as the length of the path from the
root to the node x. One edge contributes one-unit length in the path. So, the depth of
node x can also be defined as the number of edges between the root node and the
node x. The root node has 0 depth.
o Height of node x: The height of node x can be defined as the longest path from the
node x to the leaf node.

Based on the properties of the Tree data structure, trees are classified into various categories.

Implementation of Tree
The tree data structure can be created by creating the nodes dynamically with the help of the
pointers. The tree in the memory can be represented as shown below:

© Dr. Ganesh Khekare


The above figure shows the representation of the tree data structure in the memory. In the above
structure, the node contains three fields. The second field stores the data; the first field stores
the address of the left child, and the third field stores the address of the right child.

In programming, the structure of a node can be defined as:

1. struct node
2. {
3. int data;
4. struct node *left;
5. struct node *right;
6. }

The above structure can only be defined for the binary trees because the binary tree can have
utmost two children, and generic trees can have more than two children. The structure of the
node for generic trees would be different as compared to the binary tree.

Types of Tree data structure


The following are the types of a tree data structure:

o General tree: The general tree is one of the types of tree data structure. In the general
tree, a node can have either 0 or maximum n number of nodes. There is no restriction
imposed on the degree of the node (the number of nodes that a node can contain). The
topmost node in a general tree is known as a root node. The children of the parent node
are known as subtrees.

© Dr. Ganesh Khekare


There can be n number of subtrees in a general tree. In the general tree, the subtrees are
unordered as the nodes in the subtree cannot be ordered.
Every non-empty tree has a downward edge, and these edges are connected to the nodes
known as child nodes. The root node is labeled with level 0. The nodes that have the
same parent are known as siblings.
o Binary tree: Here, binary name itself suggests two numbers, i.e., 0 and 1. In a binary
tree, each node in a tree can have utmost two child nodes. Here, utmost means whether
the node has 0 nodes, 1 node or 2 nodes.

© Dr. Ganesh Khekare


o Binary Search tree: Binary search tree is a non-linear data structure in which one
node is connected to n number of nodes. It is a node-based data structure. A node can
be represented in a binary search tree with three fields, i.e., data part, left-child, and
right-child. A node can be connected to the utmost two child nodes in a binary search
tree, so the node contains two pointers (left child and right child pointer).
Every node in the left subtree must contain a value less than the value of the root node,
and every node in the right subtree must be bigger than the value of the root node.

A node can be created with the help of a user-defined data type known as struct, as shown
below:

1. struct node
2. {
3. int data;
4. struct node *left;
5. struct node *right;
6. }

The above is the node structure with three fields: data field, the second field is the left pointer
of the node type, and the third field is the right pointer of the node type.

o AVL tree

It is one of the types of the binary tree, or we can say that it is a variant of the binary search
tree. AVL tree satisfies the property of the binary tree as well as of the binary search tree. It
is a self-balancing binary search tree that was invented by Adelson Velsky Lindas. Here, self-
balancing means that balancing the heights of left subtree and right subtree. This balancing is
measured in terms of the balancing factor.

We can consider a tree as an AVL tree if the tree obeys the binary search tree as well as a
balancing factor. The balancing factor can be defined as the difference between the height of
the left subtree and the height of the right subtree. The balancing factor's value must be either
0, -1, or 1; therefore, each node in the AVL tree should have the value of the balancing factor
either as 0, -1, or 1.

© Dr. Ganesh Khekare


Binary Tree
The Binary tree means that the node can have maximum two children. Here, binary name itself
suggests that 'two'; therefore, each node can have either 0, 1 or 2 children.

Let's understand the binary tree through an example.

The above tree is a binary tree because each node contains the utmost two children. The logical
representation of the above tree is given below:

© Dr. Ganesh Khekare


In the above tree, node 1 contains two pointers, i.e., left and a right pointer pointing to the left
and right node respectively. The node 2 contains both the nodes (left and right node); therefore,
it has two pointers (left and right). The nodes 3, 5 and 6 are the leaf nodes, so all these nodes
contain NULL pointer on both left and right parts.10s

Properties of Binary Tree

o At each level of i, the maximum number of nodes is 2i.


o The height of the tree is defined as the longest path from the root node to the leaf node.
The tree which is shown above has a height equal to 2. Therefore, the maximum number
of nodes at height 2 is equal to (1+2+4) = 7. In general, the maximum number of
nodes possible at height h is (20 + 21 + 22+….2h) = 2h+1 -1.
o The minimum number of nodes possible at height h is equal to h+1.
o If the number of nodes is minimum, then the height of the tree would be maximum.
Conversely, if the number of nodes is maximum, then the height of the tree would be
minimum.

If there are 'n' number of nodes in the binary tree.

The minimum height can be computed as:

As we know that,

n = 2h+1 -1

n+1 = 2h+1

Taking log on both the sides,

log2(n+1) = log2(2h+1)

log2(n+1) = h+1

h = log2(n+1) - 1

The maximum height can be computed as:

As we know that,

n = h+1

h= n-1

© Dr. Ganesh Khekare


Types of Binary Tree
There are five types of Binary tree:

o Full/ Proper/ Strict Binary Tree


o Complete Binary Tree
o Perfect Binary Tree
o Degenerate Binary Tree
o Balanced Binary Tree

1. Full/ Proper/ Strict Binary Tree


The full binary tree is also known as a strict binary tree. The tree can only be considered as the
full binary tree if each node must contain either 0 or 2 children. The full binary tree can also
be defined as the tree in which each node must contain 2 children except the leaf nodes.

Let's look at the simple example of the Full Binary tree.

In the above tree, we can observe that each node is either containing zero or two children;
therefore, it is a Full Binary tree.

Properties of Full Binary Tree

o The number of leaf nodes is equal to the number of internal nodes plus 1. In the above
example, the number of internal nodes is 2; therefore, the number of leaf nodes is equal
to 3.

© Dr. Ganesh Khekare


o The maximum number of nodes is the same as the number of nodes in the binary tree,
i.e., 2h+1 -1.
o The minimum number of nodes in the full binary tree is 2*h-1.
o The minimum height of the full binary tree is log2(n+1) - 1.
o The maximum height of the full binary tree can be computed as:

n= 2*h - 1

n+1 = 2*h

h = n+1/2

2. Complete Binary Tree


The complete binary tree is a tree in which all the nodes are completely filled except the last
level. In the last level, all the nodes must be as left as possible. In a complete binary tree, the
nodes should be added from the left.

Let's create a complete binary tree.

The above tree is a complete binary tree because all the nodes are completely filled, and all the
nodes in the last level are added at the left first.

© Dr. Ganesh Khekare


Properties of Complete Binary Tree

o The maximum number of nodes in complete binary tree is 2h+1 - 1.


o The minimum number of nodes in complete binary tree is 2h.
o The minimum height of a complete binary tree is log2(n+1) - 1.
o The maximum height of a complete binary tree is

3. Perfect Binary Tree


A tree is a perfect binary tree if all the internal nodes have 2 children, and all the leaf nodes
are at the same level.

Let's look at a simple example of a perfect binary tree.

The below tree is not a perfect binary tree because all the leaf nodes are not at the same level.

© Dr. Ganesh Khekare


Note: All the perfect binary trees are the complete binary trees as well as the full binary tree,
but vice versa is not true, i.e., all complete binary trees and full binary trees are the perfect
binary trees.

4. Degenerate Binary Tree


The degenerate binary tree is a tree in which all the internal nodes have only one children.

Let's understand the Degenerate binary tree through examples.

The above tree is a degenerate binary tree because all the nodes have only one child. It is also
known as a right-skewed tree as all the nodes have a right child only.

© Dr. Ganesh Khekare


The above tree is also a degenerate binary tree because all the nodes have only one child. It is
also known as a left-skewed tree as all the nodes have a left child only.

5. Balanced Binary Tree


The balanced binary tree is a tree in which both the left and right trees differ by atmost 1. For
example, AVL and Red-Black trees are balanced binary tree.

Let's understand the balanced binary tree through examples.

The above tree is a balanced binary tree because the difference between the left subtree and
right subtree is zero.

© Dr. Ganesh Khekare


The above tree is not a balanced binary tree because the difference between the left subtree and
the right subtree is greater than 1.

Binary Tree Implementation

A Binary tree is implemented with the help of pointers. The first node in the tree is represented
by the root pointer. Each node in the tree consists of three parts, i.e., data, left pointer and right
pointer. To create a binary tree, we first need to create the node. We will create the node of
user-defined as shown below:

1. struct node
2. {
3. int data,
4. struct node *left, *right;
5. }

In the above structure, data is the value, left pointer contains the address of the left node,
and right pointer contains the address of the right node.

© Dr. Ganesh Khekare


Tree Traversals (Inorder, Preorder and Postorder)
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one
logical way to traverse them, trees can be traversed in different ways. The following are the
generally used methods for traversing trees:
Inorder Traversal: (left-root-right)
Algorithm:
1. Traverse the left subtree, i.e., call Inorder(left->subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right->subtree)
Uses of Inorder Traversal:
In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing
order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where
Inorder traversal is reversed can be used.

Preorder Traversal: (root- left-right)


Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left->subtree)
3. Traverse the right subtree, i.e., call Preorder(right->subtree)

Uses of Preorder:
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get
prefix expressions on an expression tree.

Postorder Traversal: (left-right-root)


Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left->subtree)
2. Traverse the right subtree, i.e., call Postorder(right->subtree)
3. Visit the root

Uses of Postorder:
Postorder traversal is used to delete the tree. Postorder traversal is also useful to get the
postfix expression of an expression tree

© Dr. Ganesh Khekare


Examples:

© Dr. Ganesh Khekare


Now the same above tree
Preorder: A B D H I E C F J G K L
Postorder: H I D E B J F K L G C A

© Dr. Ganesh Khekare


Binary Search tree
10s
What is a Binary Search tree?
A binary search tree follows some order to arrange the elements. In a Binary search tree, the
value of left node must be smaller than the parent node, and the value of right node must
be greater than the parent node. This rule is applied recursively to the left and right subtrees
of the root.
Let's understand the concept of Binary search tree with an example.

In the above figure, we can observe that the root node is 40, and all the nodes of the left subtree
are smaller than the root node, and all the nodes of the right subtree are greater than the root
node.
Similarly, we can see the left child of root node is greater than its left child and smaller than its
right child. So, it also satisfies the property of binary search tree. Therefore, we can say that
the tree in the above image is a binary search tree.
Suppose if we change the value of node 35 to 55 in the above tree, check whether the tree will
be binary search tree or not.

In the above tree, the value of root node is 40, which is greater than its left child 30 but smaller
than right child of 30, i.e., 55. So, the above tree does not satisfy the property of Binary search
tree. Therefore, the above tree is not a binary search tree.

© Dr. Ganesh Khekare


Advantages of Binary Search Tree
o Searching an element in the Binary search tree is easy as we always have a hint that
which subtree has the desired element.
o As compared to array and linked lists, insertion and deletion operations are faster in
BST.

Example of creating a binary search tree


Now, let's see the creation of binary search tree using an example.
Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50
o First, we have to insert 45 into the tree as the root of the tree.
o Then, read the next element; if it is smaller than the root node, insert it as the root of
the left subtree, and move to the next element.
o Otherwise, if the element is larger than the root node, then insert it as the root of the
right subtree.
Now, let's see the process of creating the Binary search tree using the given data element. The
process of creating the BST is shown below -
Step 1 - Insert 45.

Step 2 - Insert 15.


As 15 is smaller than 45, so insert it as the root node of the left subtree.

Step 3 - Insert 79.


As 79 is greater than 45, so insert it as the root node of the right subtree.

© Dr. Ganesh Khekare


Step 4 - Insert 90.
90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.

Step 5 - Insert 10.


10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.

© Dr. Ganesh Khekare


Step 6 - Insert 55.
55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree of 79.

Step 7 - Insert 12.


12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the right subtree of 10.

Step 8 - Insert 20.


20 is smaller than 45 but greater than 15, so it will be inserted as the right subtree of 15.

© Dr. Ganesh Khekare


Step 9 - Insert 50.
50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a left subtree of 55.

Now, the creation of binary search tree is completed. After that, let's move towards the
operations that can be performed on Binary search tree.
We can perform insert, delete and search operations on the binary search tree.
Let's understand how a search is performed on a binary search tree.

© Dr. Ganesh Khekare


Searching in Binary Search Tree
Searching means to find or locate a specific element or node in a data structure. In Binary
search tree, searching a node is easy because elements in BST are stored in a specific order.
The steps of searching a node in Binary Search tree are listed as follows -
1. First, compare the element to be searched with the root element of the tree.
2. If root is matched with the target element, then return the node's location.
3. If it is not matched, then check whether the item is less than the root element, if it is
smaller than the root element, then move to the left subtree.
4. If it is larger than the root element, then move to the right subtree.
5. Repeat the above procedure recursively until the match is found.
6. If the element is not found or not present in the tree, then return NULL.
Now, let's understand the searching in binary tree using an example. We are taking the binary
search tree formed above. Suppose we have to find node 20 from the below tree.
Step1:

Step2:

Step3:

© Dr. Ganesh Khekare


Now, let's see the algorithm to search an element in the Binary search tree.
Algorithm to search an element in Binary search tree
1. Search (root, item)
2. Step 1 - if (item = root → data) or (root = NULL)
3. return root
4. else if (item < root → data)
5. return Search(root → left, item)
6. else
7. return Search(root → right, item)
8. END if
9. Step 2 - END
Now let's understand how the deletion is performed on a binary search tree. We will also see
an example to delete an element from the given tree.

Deletion in Binary Search tree


In a binary search tree, we must delete a node from the tree by keeping in mind that the property
of BST is not violated. To delete a node from BST, there are three possible situations occur -
o The node to be deleted is the leaf node, or,
o The node to be deleted has only one child, and,
o The node to be deleted has two children

We will understand the situations listed above in detail.


When the node to be deleted is the leaf node
It is the simplest case to delete a node in BST. Here, we have to replace the leaf node with
NULL and simply free the allocated space.
We can see the process to delete a leaf node from BST in the below image. In below image,
suppose we have to delete node 90, as the node to be deleted is a leaf node, so it will be replaced
with NULL, and the allocated space will free.

© Dr. Ganesh Khekare


When the node to be deleted has only one child
In this case, we have to replace the target node with its child, and then delete the child node. It
means that after replacing the target node with its child node, the child node will now contain
the value to be deleted. So, we simply have to replace the child node with NULL and free up
the allocated space.
We can see the process of deleting a node with one child from BST in the below image. In the
below image, suppose we have to delete the node 79, as the node to be deleted has only one
child, so it will be replaced with its child 55.
So, the replaced node 79 will now be a leaf node that can be easily deleted.

When the node to be deleted has two children


This case of deleting a node in BST is a bit complex among other two cases. In such a case, the
steps to be followed are listed as follows -
o First, find the inorder successor / inorder predecessor of the node to be deleted.
o After that, replace that node with the inorder successor / inorder predecessor until the
target node is placed at the leaf of tree.
o And at last, replace the node with NULL and free up the allocated space.
The inorder successor is required when the right child of the node is not empty. We can obtain
the inorder successor by finding the minimum element in the right subtree. Vice versa if
required we can obtain the inorder predecessor by finding maximum element in left subtree.
We can see the process of deleting a node with two children from BST in the below image. In
the below image, suppose we have to delete node 45 that is the root node, as the node to be
deleted has two children, so it will be replaced with its inorder successor. Now, node 45 will
be at the leaf of the tree so that it can be deleted easily.

© Dr. Ganesh Khekare


Now let's understand how insertion is performed on a binary search tree.

Insertion in Binary Search tree


A new key in BST is always inserted at the leaf. To insert an element in BST, we have to start
searching from the root node; if the node to be inserted is less than the root node, then search
for an empty location in the left subtree. Else, search for the empty location in the right subtree
and insert the data. Insert in BST is similar to searching, as we always have to maintain the rule
that the left subtree is smaller than the root, and right subtree is larger than the root.
Now, let's see the process of inserting a node into BST using an example.

The complexity of the Binary Search tree


Let's see the time and space complexity of the Binary search tree. We will see the time
complexity for insertion, deletion, and searching operations in best case, average case, and
worst case.

© Dr. Ganesh Khekare


1. Time Complexity
Operations Best case time Average case time Worst case time
complexity complexity complexity

Insertion O(log n) O(log n) O(n)

Deletion O(log n) O(log n) O(n)

Search O(log n) O(log n) O(n)


Where 'n' is the number of nodes in the given tree.
2. Space Complexity
Operations Space complexity

Insertion O(n)

Deletion O(n)

Search O(n)

o The space complexity of all operations of Binary search tree is O(n).

© Dr. Ganesh Khekare


Find maximum (or minimum) in Binary Tree
Given a Binary Tree, find the maximum (or minimum) element in it. For example, maximum
in the following Binary Tree is 9.

Max and Min element in Binary Tree


In Binary Search Tree, we can find maximum by traversing right pointers until we reach the
rightmost node. But in Binary Tree, we must visit every node to figure out maximum. So, the
idea is to traverse the given tree and for every node return maximum of 3 values.
1. Node’s data.
2. Maximum in node’s left subtree.
3. Maximum in node’s right subtree.

Below is the implementation of above approach.


// C program to find maximum and minimum in a Binary Tree
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

// A tree node
struct Node
{
int data;
struct Node *left, *right;
};

// A utility function to create a new node


struct Node* newNode(int data)

© Dr. Ganesh Khekare


{
struct Node* node
= (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}

// Returns maximum value in a given Binary Tree


int findMax(struct Node* root)
{
// Base case
if (root == NULL)
return INT_MIN;

// Return maximum of 3 values:


// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMax(root->left);
int rres = findMax(root->right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}

// Driver code
int main(void)
{
struct Node* NewRoot = NULL;
struct Node* root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);

// Function call
printf("Maximum element is %d \n", findMax(root));

return 0;
}

Output
Maximum element is 11

© Dr. Ganesh Khekare


Time Complexity: O(N), where N is number of nodes as every node of tree is traversed
once by findMax() and findMin().
Auxiliary Space: O(N) , Recursive call for each node tree considered as stack space.
Similarly, we can find the minimum element in a Binary tree by comparing three values.
Below is the function to find a minimum in Binary Tree.
// Returns minimum value in a given Binary Tree
int findMin(struct Node* root)
{
// Base case
if (root == NULL)
return INT_MAX;

// Return minimum of 3 values:


// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMin(root->left);
int rres = findMin(root->right);
if (lres < res)
res = lres;
if (rres < res)
res = rres;
return res;
}

Complexity Analysis:
Time Complexity: O(N).
In the recursive function calls, every node of the tree is processed once and hence the
complexity due to the function is O(N) if there are total N nodes in the tree. Therefore, the
time complexity is O(N).
Space Complexity: O(N).
Recursive call is happening. The every node is processed once and considering the stack
space, the space complexity will be O(N).

Find maximum and minimum element in binary tree without using recursion or stack
or queue
Given a binary tree. The task is to find out the maximum and minimum element in a binary
tree without using recursion or stack or queue i.e, space complexity should be O(1).
Examples:
Input :
12
/ \
13 10
/ \
14 15
/ \ / \
21 24 22 23

© Dr. Ganesh Khekare


Output : Max element : 24
Min element : 10

Input :
12
/ \
19 82
/ / \
41 15 95
\ / / \
2 21 7 16

Output : Max element : 95


Min element : 2

Approach :
1. Initialize current as root
2. Take to variable max and min
3. While current is not NULL
• If the current does not have left child
• Update variable max and min with current’s data if required
• Go to the right, i.e., current = current->right
• Else
• Make current as the right child of the rightmost
node in current’s left subtree
• Go to this left child, i.e., current = current->left

© Dr. Ganesh Khekare


Find k-th smallest element in BST (Order Statistics in BST) / Finding Min
and Max:
Given the root of a binary search tree and K as input, find Kth smallest element in BST.
For example, in the following BST, if k = 2, then the output should be 10, and if k = 4, then
the output should be 14. (assuming counting start with index number 0)
The inorder of given BST is 4 8 10 12 14 20 22

Method 1: Using Inorder Traversal (O(n) time and O(h) auxiliary space)
The Inorder Traversal of a BST traverses the nodes in increasing order. So, the idea is to
traverse the tree in Inorder. While traversing, keep track of the count of the nodes visited. If
the count becomes k, print the node.
Time complexity: O(h) where h is the height of the tree.
Auxiliary Space: O(h)

We can optimize space using Morris Traversal. In Morris traversal, we first create links to
Inorder successor and print the data using these links, and finally revert the changes to restore
original tree. In this case,
Time Complexity: O(n) where n is the size of BST
Auxiliary Space: O(1)

Method 2: Using Any Tree Traversal (pre-in-post) than return kth smallest easily.
Approach:
Here we use pre order traversal than sort it and return the kth smallest element.
Algorithm:
Here we have tree we will take preorder of it as :

© Dr. Ganesh Khekare


preorder will : 20 8 4 12 10 14 22

And store it in array/vector.


After taking preorder we will sort it and than return k-1 element from the array.
Complexity Analysis:
Time Complexity: O(nlogn) i.e O(n) time for preorder and nlogn time for sorting.
Auxiliary Space: O(n) i.e for vector/array storage.

Method 3: Augmented Tree Data Structure (O(h) Time Complexity and O(h) auxiliary
space)
The idea is to maintain the rank of each node. We can keep track of elements in the left
subtree of every node while building the tree. Since we need the K-th smallest element, we
can maintain the number of elements of the left subtree in every node.
Assume that the root is having ‘lCount’ nodes in its left subtree. If K = lCount + 1, root is K-
th node. If K < lCount + 1, we will continue our search (recursion) for the Kth smallest
element in the left subtree of root. If K > lCount + 1, we continue our search in the right
subtree for the (K – lCount – 1)-th smallest element. Note that we need the count of elements
in the left subtree only.
Time complexity: O(h) where h is the height of the tree.
Auxiliary Space: O(h)

Method 4: Iterative approach using Stack: The basic idea behind the Iterative Approach
using Stack to find the kth smallest element in a Binary Search Tree (BST) is to traverse the
tree in an inorder fashion using a stack until we find the kth smallest element. Follow the
steps to implement the above idea:
1. Create an empty stack and set the current node to the root of the BST.
2. Push all the left subtree nodes of the current node onto the stack until the current
node is NULL.
3. Pop the top node from the stack and check if it is the k-th element. If it is, return
its value.
4. Decrement the value of k by 1.
5. Set the current node to the right child of the popped node.
6. Go to step 2 if the stack is not empty or k is not equal to 0.

© Dr. Ganesh Khekare


Time Complexity: O(h+ k), The time complexity of the Iterative Approach using Stack to
find the kth smallest element in a BST is O(h + k), where h is the height of the BST and k is
the value of k.
Auxiliary Space: O(h+k), The space complexity of the code is O(h + k), where h is the
height of the BST and k is the maximum size of the stack.

© Dr. Ganesh Khekare


Construct a Binary Tree from Preorder and Inorder:

Construct a Binary Tree from Postorder and Inorder:

© Dr. Ganesh Khekare


Construct a Binary Tree from Preorder and Postorder:
1. If only Preorder and Postorder is given then it is not possible to construct
unique binary tree.
2. If only Preorder and Postorder is given then it is possible to construct unique
full binary tree.

© Dr. Ganesh Khekare


Construct of BST when only Preorder or Postorder is Given:
Only Preorder:

© Dr. Ganesh Khekare


Only Postorder:

© Dr. Ganesh Khekare

You might also like