File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ '''
2+ Aim: To form a Binary Search Tree of the integers entered and display its height.
3+
4+ '''
5+
6+ # initializing the tree
7+ class Node :
8+ def __init__ (self ,data ):
9+ self .right = self .left = None
10+ self .data = data
11+
12+ class Solution :
13+ # function for inserting values according to BST rules
14+ def insert (self ,root ,data ):
15+ if root == None :
16+ return Node (data )
17+ else :
18+ if data <= root .data :
19+ cur = self .insert (root .left ,data )
20+ root .left = cur
21+ else :
22+ cur = self .insert (root .right ,data )
23+ root .right = cur
24+ return root
25+
26+ # calculating the height of the tree
27+ def getHeight (self ,root ):
28+ if root == None :
29+ return - 1
30+ return 1 + max (self .getHeight (root .left ), self .getHeight (root .right ))
31+
32+ # getting the input for total number of integers to be entered
33+ T = int (input ())
34+ # making an object of the class
35+ myTree = Solution ()
36+ root = None
37+
38+ # inserting values
39+ for i in range (T ):
40+ data = int (input ())
41+ root = myTree .insert (root ,data )
42+ # geeting the height calculated
43+ height = myTree .getHeight (root )
44+
45+ # printing the result
46+ print ("Height of BST:" ,height )
47+
48+ '''
49+
50+ COMPLEXITY:
51+
52+ Time Complexity -> O(N)
53+ Space Complexity -> O(N)
54+
55+ Sample Input:
56+ 7
57+ 3
58+ 5
59+ 2
60+ 1
61+ 4
62+ 6
63+ 7
64+ Sample Output:
65+ Height of BST: 3
66+
67+ Explaination:
68+ The BST looks something like this:
69+
70+ 3
71+ 2 5
72+ 1 4 6
73+ 7
74+
75+ So, the height is --> 3.
76+
77+ '''
You can’t perform that action at this time.
0 commit comments