forked from lanqiao-courses/python-100
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path033-tree_next.py
More file actions
28 lines (23 loc) · 812 Bytes
/
033-tree_next.py
File metadata and controls
28 lines (23 loc) · 812 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
27
28
from bst import Node
class BstSuccessor(object):
def get_next(self, node):
if node is None:
raise TypeError('node cannot be None')
if node.right is not None:
return self._left_most(node.right)
else:
return self._next_ancestor(node)
def _left_most(self, node):
if node.left is not None:
return self._left_most(node.left)
else:
return node.data
def _next_ancestor(self, node):
if node.parent is not None:
if node.parent.data > node.data:
return node.parent.data
else:
return self._next_ancestor(node.parent)
# We reached the root, the original input node
# must be the largest element in the tree.
return None