-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathsecond-largest-node-in-bst.py
87 lines (71 loc) · 1.75 KB
/
second-largest-node-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
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
81
82
83
84
85
86
87
"""
#36
Dropbox
This problem was asked by Dropbox.
Given the root to a binary search tree, find the second largest node in the tree.
"""
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return "< " + str(self.val) + " >"
def findSecondMax(root):
if root.right:
# Finding the second max using max
maxNode = root
secondMaxNode = None
while maxNode.right:
secondMaxNode = maxNode
maxNode = maxNode.right
if maxNode.left:
secondMaxNode = maxNode.left
while secondMaxNode.right:
secondMaxNode = secondMaxNode.right
return secondMaxNode
elif root.left:
# Finding the right most node in the left subtree
secondMaxNode = root.left
while secondMaxNode.right:
secondMaxNode = secondMaxNode.right
return secondMaxNode
else:
# No second maximum node
return None
def main():
"""
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
"""
BST = Node(8, Node(3, Node(1), Node(6, Node(4), Node(7))), Node(10, None, Node(14, Node(13))))
print(findSecondMax(BST))
"""
8
/ \
3 10
/ \ \
1 6 14
/ \
4 7
"""
BST = Node(8, Node(3, Node(1), Node(6, Node(4), Node(7))), Node(10, None, Node(14)))
print(findSecondMax(BST))
"""
8
/
3
/ \
1 6
/ \
4 7
"""
BST = Node(8, Node(3, Node(1), Node(6, Node(4), Node(7))))
print(findSecondMax(BST))
if __name__ == "__main__":
main()