forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecond_largest_in_bst.py
55 lines (39 loc) · 1.06 KB
/
second_largest_in_bst.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
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def find_largest(root):
curr = root
while curr:
if not curr.right:
return curr.val
curr = curr.right
def second_largest(root):
if not root or (not root.left and not root.right):
return "BST should have atleast 2 nodes"
curr = root
while curr:
if curr.left and not curr.right:
return find_largest(curr.left)
if curr.right and not curr.right.left and not curr.right.right:
return curr.val
curr = curr.right
def insert(root, key):
if root == None:
return Node(key)
if key < root.val:
root.left = insert(root.left, key)
elif key > root.val:
root.right = insert(root.right, key)
return root
if __name__ == '__main__':
root = Node(6)
insert(root, 5)
insert(root, 3)
insert(root, 10)
insert(root, 4)
insert(root, 11)
insert(root, 14)
insert(root, 1)
print(second_largest(root))