Inorder Successor in BST
recursive:
If target node is smaller than its parent, just choose left child and do the recursion.
If parent is greater than and equal to target node, choose the right child
# 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 root
if root.val > p.val:
left = self.inorderSuccessor(root.left, p)
if left == None:
return root
else:
return left
else:
return self.inorderSuccessor(root.right, p)
iteration:
# 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 root
successor = None
while root:
if root.val > p.val:
successor = root
root = root.left
else:
root = root.right
return successor