# 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:
return None
traverse = []
self.inOrder(root, traverse)
if traverse[-1] == p:
return None
for i in range(len(traverse) - 1):
if traverse[i] == p:
return traverse[i + 1]
return None
def inOrder(self, root, traverse):
if not 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):
class Solution(object):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
successor = None
current = root
while current:
if p.val < current.val:
successor = current
current = current.left
else:
current = current.right
return successor