class Solution(object):
"""
@param root <TreeNode>: The root of the BST.
@param p <TreeNode>: You need find the successor node of p.
@return <TreeNode>: Successor of p.
"""
def inorderSuccessor(self, root, p):
if root is None or p is None:
return None
successor = None
while root is not None and root.val != p.val: #p点的后继节点一定就是root.val > p.val
if root.val > p.val:
successor = root
root = root.left
else:
root = root.right
if root is None: #找不到p点的时候,跳出
return None
if root.right is None: #如果没有右节点,当前节点p==root 那么直接返回后续节点,就是从root过来的
return successor
root = root.right
while root.left is not None: #如果有右节点,当前节点p==root 那么p点的后续是右子树的最小值,也就是最左左节点。
root = root.left
return root