forked from lanqiao-courses/python-100
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path034-second_largest.py
More file actions
26 lines (21 loc) · 847 Bytes
/
034-second_largest.py
File metadata and controls
26 lines (21 loc) · 847 Bytes
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
from bst import Bst
class Solution(Bst):
def find_second_largest(self):
if self.root is None:
raise TypeError('root cannot be None')
if self.root.right is None and self.root.left is None:
raise ValueError('root must have at least one child')
return self._find_second_largest(self.root)
def _find_second_largest(self, node):
if node.right is not None:
if node.right.left is not None or node.right.right is not None:
return self._find_second_largest(node.right)
else:
return node
else:
return self._find_right_most_node(node.left)
def _find_right_most_node(self, node):
if node.right is not None:
return self._find_right_most_node(node.right)
else:
return node