-
Notifications
You must be signed in to change notification settings - Fork 1
/
BinarySearchTreeHR.py
80 lines (63 loc) · 1.98 KB
/
BinarySearchTreeHR.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
Task
The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, , pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.
Input Format
The locked stub code in your editor reads the following inputs and assembles them into a binary search tree:
The first line contains an integer, , denoting the number of nodes in the tree.
Each of the subsequent lines contains an integer, , denoting the value of an element that must be added to the BST.
Output Format
The locked stub code in your editor will print the integer returned by your getHeight function denoting the height of the BST.
Sample Input
7
3
5
2
1
4
6
7
Sample Output
3
Explanation
The input forms the following BST:
BST.png
The longest root-to-leaf path is shown below:
Longest RTL.png
There are nodes in this path that are connected by edges, meaning our BST's . Thus, we print as our answer.
"""
# SOLUTION
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def getHeight(self,root):
#Write your code here
if root == None :
return -1
else :
leftHeight = myTree.getHeight(root.left)
rightHeight = myTree.getHeight(root.right)
if leftHeight > rightHeight :
return 1+leftHeight
else :
return 1+rightHeight
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
height=myTree.getHeight(root)
print(height)