-
Notifications
You must be signed in to change notification settings - Fork 8
/
findSuccessor.py
41 lines (34 loc) · 1.11 KB
/
findSuccessor.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
# This is an input class. Do not edit.
class BinaryTree:
def __init__(self, value, left=None, right=None, parent=None):
self.value = value
self.left = left
self.right = right
self.parent = parent
# def findSuccessor(tree, node):
# visited = []
# findSuccessorHelper(tree, node, visited)
# for i in range(len(visited)):
# if visited[i] == node:
# return visited[i+1]
# return None
# def findSuccessorHelper(tree, node, visited):
# if tree is None:
# return None
# findSuccessorHelper(tree.left, node, visited)
# visited.append(tree)
# findSuccessorHelper(tree.right, node, visited)
def findSuccessor(tree, node):
if node.right is not None:
return getLeftMostChild(node.right)
return getRightMostParent(node)
def getLeftMostChild(node):
current = node
while current.left is not None:
current=current.left
return current
def getRightMostParent(node):
current = node
while current.parent is not None and current.parent.right == current:
current=current.parent
return current.parent