forked from devAmoghS/Python-Interview-Problems-for-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_second_largest.py
38 lines (29 loc) · 1002 Bytes
/
find_second_largest.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
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def find_largest(root):
current = root
while current is not None:
if current.right is not None:
return current.right.data
current = current.right
def find_second_largest(root):
if root is None or (root.left is None and root.right is None):
raise ValueError("Tree must atleast have 2 nodes")
current = root
while current is not None:
if(current.left is not None and current.right is None):
return find_largest(current.left)
if(current.right is not None and current.right.left is None and current.right.right is None):
return current.data
current = current.right
node = Node(10)
node.left = Node(5)
node.left.left = Node(1)
node.right = Node(50)
node.right.left = Node(45)
node.right.right = Node(100)
result = find_second_largest(node)
print(result)