285 Inorder Successor in BST
# 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 - the actual root of the tree
:type p: TreeNode - find the next in order successor of this node
:rtype: TreeNode
"""
if not root or not p:
return None
# case 1
if p.right:
p = p.right
while p.left:
p = p.left
return p
# case 2
prev = None
while root != p:
if p.val > root.val:
root = root.right
else:
prev = root
root = root.left
return prevLast updated