# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution(object):definorderSuccessor(self,root,p):""" :type root: TreeNode :type p: TreeNode :rtype: TreeNode """ifnot root:returnNone traverse = [] self.inOrder(root, traverse)if traverse[-1]== p:returnNonefor i inrange(len(traverse) -1):if traverse[i]== p:return traverse[i +1]returnNonedefinOrder(self,root,traverse):ifnot root:return self.inOrder(root.left, traverse)# don't forget tO pass all parameters to the function traverse.append(root) self.inOrder(root.right, traverse)# don't forget tO pass all parameters to the function
Iterative (Fast):
classSolution(object):definorderSuccessor(self,root,p):""" :type root: TreeNode :type p: TreeNode :rtype: TreeNode """ successor =None current = rootwhile current:if p.val < current.val: successor = current current = current.leftelse: current = current.rightreturn successor