-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsuccessor_LCCI.py
More file actions
31 lines (25 loc) · 847 Bytes
/
successor_LCCI.py
File metadata and controls
31 lines (25 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
27
28
29
30
31
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.has_find = False
self.cur_node = None
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
self.inorder_traversal(root, p)
return self.cur_node
def inorder_traversal(self, node: TreeNode, p: TreeNode) -> None:
if node.left:
self.inorder_traversal(node.left, p)
if not self.has_find and node.val == p.val:
self.has_find = True
elif self.has_find and not self.cur_node:
self.cur_node = node
return
elif self.cur_node:
return
if node.right:
self.inorder_traversal(node.right, p)