0% found this document useful (0 votes)
17 views11 pages

DSA Pract08

Uploaded by

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

DSA Pract08

Uploaded by

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

ITU324-Data Structures and Algorithms Laboratory

Practical No-8

AIM:- (Binary Search Tree) Construct all possible BSTs for keys 1 to N and display the post
order traversal of each tree.

THEORY :-
Tree represents the nodes connected by edges. We will discuss binary tree or binary search tree
specifically.
Binary Tree is a special data structure used for data storage purposes. A binary tree has a special
condition that each node can have a maximum of two children. A binary tree has the benefits of
both an ordered array and a linked list as search is as quick as in a sorted array and insertion or
deletion operation are as fast as in linked list.

Important Terms
Following are the important terms with respect to tree.
 Path − Path refers to the sequence of nodes along the edges of a tree.
 Root − The node at the top of the tree is called root. There is only one root per tree and
one path from the root node to any node.
 Parent − Any node except the root node has one edge upward to a node called parent.

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

 Child − The node below a given node connected by its edge downward is called its child
node.
 Leaf − The node which does not have any child node is called the leaf node.
 Subtree − Subtree represents the descendants of a node.
 Visiting − Visiting refers to checking the value of a node when control is on the node.
 Traversing − Traversing means passing through nodes in a specific order.
 Levels − Level of a node represents the generation of a node. If the root node is at level
0, then its next child node is at level 1, its grandchild is at level 2, and so on.
 keys − Key represents a value of a node based on which a search operation is to be
carried out for a node.

Uses of Inorder
In 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
s reversed, can be used.

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

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.
* Pre-order traversal
1. Print the data at the root
2. Recursively print out all data in the left subtree
3. Recursively print out all data in the right subtree
* Preorder traversal
1. node, left, right
2. prefix expression
3. ++a*bc*+*defg

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

* Postorder traversal
i. left, right, node
ii. postfix expression
iii. abc*+de*f+g*+
* Inorder traversal
i. left, node, right.
ii. infix expression
iii. a+b*c+d*e+f*g

Binary Search Tree

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
properties −

 The value of the key of the left sub-tree is less than the value of its parent (root) node's
key.
 The value of the key of the right sub-tree is greater than or equal to the value of its parent
(root) node's key.

Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree and
can be defined as − left_subtree (keys) < node (key) ≤ right_subtree (keys)

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

How many structurally unique BSTs for keys from 1..N


For example, for N = 2, there are 2 unique BSTs

1 2

\ /

2 1

For example, for N =3, there are 5 unique BSTs

For n number of keys possible BSTs will be 2n Cn /n+1

How to construct all BST for keys 1…N?


The idea is to maintain a list of roots of all BSTs. Recursively construct all possible left and right
subtrees. Create a tree for every pair of left and right subtree and add the tree to list. Below is
detailed algorithm.
1) Initialize list of BSTs as empty.
2) For every number i where i varies from 1 to N, do following
......a) Create a new node with key as 'i', let this node be 'node'
......b) Recursively construct list of all left subtrees.
......c) Recursively construct list of all right subtrees.

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

3) Iterate for all left subtrees


a) For current left subtree, iterate for all right subtrees
Add current left and right subtrees to 'node' and add
'node' to list.
f(n) = total number of BSTs with '1' as root + total number of BSTs with '2' as root
+ ... + total number of BSTs with 'n' as root
f(n) = f(0)f(n-1) + f(1)f(n-2) + f(2)f(n-3) + ... + f(n-2)f(1) + f(n-1)f(0)
base cases are defined as f(0) = 1 and f(1) = 1, since number of BSTs possible with
0 or 1 distinct keys is 1.
The time complexity of this algorithm is O(n^2). This is because f(n) makes 2*(n-1)
recursive calls, then f(n-1) makes 2*(n-2) recursive calls and so on. Total number of
recursive calls made would be 2(n-1 + n-2 + n-3 + ... + 1) which is O(n^2) recursive
calls. Note that because we are storing the intermediate results, though each f(i)
occurs twice while evaluating f(n), we need to compute f(i) only once which avoids
exponential running time for this algorithm.

Algorithm: PostOrder Traversal


POSTORD(INFO,LEFT,RIGHT,ROOT)
A binary tree T is in memory. This algorithm does a postorder traversal of T , applying an
operation PROCESS to each of its nodes. An array STACK is used to temporarily hold the
addresses of nodes.
1. [Push NULL onto STACK and initialize PTR.]
Set TOP:=1,STACK[1]:=NULL and PTR:=ROOT.
2. [Push left-most path onto STACK.]
Repeat steps 3 to 5 while PTR!=NULL:
3.Set TOP:=TOP+1 and STACK [TOP]:=PTR.[Pushes PTR on STACK].
4.If RIGHT[PTR]!=NULL , then :[Push on STACK] Set TOP:=TOP+1 and STACK[TOP]:=-
RIGHT[PTR][End of If structure.]
5.Set PTR:=LEFT[PTR].[Updates pointer PTR.] [End of step 2 loop.]
6.Set PTR:=STACK[TOP] and TOP:=TOP-1. [Pops node from STACK.]
7.Repeat while PTR>0:

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

(a)Apply PROCESS to INFO[PTR].


(b)Set PTR:=STACK[TOP] and TOP:=TOP-1.
[pops node from STACK.]
[End of loop.]
8.If PTR<0,then:
(a)Set PTR:=-PTR.
(b)Go to step 2.
[End of If structure.]
9.Exit.

Source code:-
from drawtree import draw_bst

class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None

@staticmethod
def display(root, l):
if root is not None:
l.append(root.data)
Node.display(root.left, l)
Node.display(root.right, l)

@staticmethod
def postorder(root):
if root is not None:
Node.postorder(root.left)
Node.postorder(root.right)
print(root.data, end=" ")

@staticmethod
def construct(start, end):
list_of_trees = []
if start > end:
list_of_trees.append(None)
return list_of_trees

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

for i in range(start, end + 1):


lefttree = Node.construct(start, i - 1)
righttree = Node.construct(i + 1, end)

for left in lefttree:


for right in righttree:
newnode = Node(i)
newnode.left = left
newnode.right = right
list_of_trees.append(newnode)
return list_of_trees

# Get input from user


n1 = int(input("Enter limit n1: "))
n2 = int(input("Enter limit n2: "))

# Construct all BSTs


alltrees = Node.construct(n1, n2)

# Display all constructed BSTs


print("All constructed BSTs are:")
for tree in alltrees:
l = []
Node.display(tree, l) # Pass 'l' to collect nodes in pre-order
draw_bst(l)
print("\n" + "--" * 5 + "\n")

# Post-order traversal of all BSTs


print("Postorder traversal of all BSTs:")
a=0
for tree in alltrees:
Node.postorder(tree)
a += 1
print() # To separate trees

# Display total number of different BSTs


print("\nTotal number of different BSTs are:", a)

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

Output:-

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

Viva Questions:-
 Define tree, Binary tree
Ans:-
l)Tree: Tree is a hierarchical data structure. A tree is a finite set of nodes that has a
distinguished node called the root node.
Remaining nodes of the tree forms disjoint sets of nodes. These sets are again trees. Each
of which is called subtree of root node.
Binary Tree: A binary tree is a tree in which every node can have at the most two
children.
It is a finite set of elements called nodes such that either Tree is empty or It contains a
root node R and remaining nodes forms two sets of disjoint binary trees called left
subtree and right subtree of R.
So a binary tree may be either empty or contains a distinguished node called root node.
Root node is the top most node of the tree. If there are more than one node then
remaining nodes belong to either left or the right subtree of root node.

 How to perform postorder traversal of a tree


Ans:-
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

 How would you print out the data in a binary tree, level by level, starting at the top?
Ans:- A simple solution is to print using the recursive function discussed in the level
order traversal post and print a new line after every call to printGivenLevel().

Find height of tree and run depth first search and maintain current height, print nodes
for every height from root and for 1 to height.

 Write a function to find the depth of a binary tree.

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

Ans:-
int maxDepth(node* node)
{
if (node == NULL)
return 0;
else {
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);

/* use the larger one */


if (lDepth > rDepth)
return (lDepth + 1);
else
return (rDepth + 1);
}
}

 What is binary search tree?


Ans:-
Binary Search Tree is a node-based binary tree data structure which has the following
properties:
1. The left subtree of a node contains only nodes with keys lesser than the node’s key.
2. The right subtree of a node contains only nodes with keys greater than the node’s key.
3. The left and right subtree each must also be a binary search tree.

 The pre-order traversal of a binary search tree is given by 12, 8, 6, 2, 7, 9, 10, 16, 15, 19,
17, 20.
Then the post-order traversal of this tree is:
(A) 2, 6, 7, 8, 9, 10, 12, 15, 16, 17, 19, 20 (B) 2, 7, 6, 10, 9, 8, 15, 17, 20, 19, 16, 12
(C) 7, 2, 6, 8, 9, 10, 20, 17, 19, 15, 16, 12 (D) 7, 6, 2, 10, 9, 8, 15, 16, 17, 20, 19, 12

Department of Information Technology, GCoE, Amravati Winter 2022


ITU324-Data Structures and Algorithms Laboratory

 A binary tree T has n leaf nodes. The number of nodes of degree 2 in T is


(a) log2n (b) n-1 (c) n (d) 2n

 A binary search tree contains the value 1, 2, 3, 4, 5, 6, 7, 8. The tree is traversed in pre-
order and the values are printed out. Which of the following sequences is a valid output?
(a) 5 3 1 2 4 7 8 6 (b) 5 3 1 2 6 4 8 7 (c) 5 3 2 4 1 6 7 8 (d) 5 3 1 2 4 7 6 8

 Consider the following nested representation of binary trees: (X Y Z) indicates Y and Z


are the left and right sub stress, respectively, of node X. Note that Y and Z may be
NULL, or further nested. Which of the following represents a valid binary tree?
(a) (1 2 (4 5 6 7))
(b) (1 ((2 3 4) 5 6) 7)
(c) (1 (2 3 4)(5 6 7))
(d) (1 (2 3 NULL) (4 5))

 The preorder traversal sequence of a binary search tree is 30, 20, 10, 15, 25, 23, 39, 35,
42. Which one of the following is the postorder traversal sequence of the same tree?
(GATE 2013)
(A) 10, 20, 15, 23, 25, 35, 42, 39, 30
(B) 15, 10, 25, 23, 20, 42, 35, 39, 30
(C) 15, 20, 10, 23, 25, 42, 35, 39, 30
(D) 15, 10, 23, 25, 20, 35, 42, 39, 30

Department of Information Technology, GCoE, Amravati Winter 2022

You might also like