-
Notifications
You must be signed in to change notification settings - Fork 613
/
285.py
37 lines (32 loc) · 795 Bytes
/
285.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
'''
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
if not root or not p:
return None
if p.right:
p = p.right
while p.left:
p = p.left
return p
successor = None
while root and root != p:
if root.val > p.val:
successor = root
root = root.left
else:
root = root.right
return successor