Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created September 23, 2018 20:55
Show Gist options
  • Select an option

  • Save yokolet/46e6be0c88dc17a1c8e9d1be33fb9a7b to your computer and use it in GitHub Desktop.

Select an option

Save yokolet/46e6be0c88dc17a1c8e9d1be33fb9a7b to your computer and use it in GitHub Desktop.
Inorder Successor in BST
"""
Description:
Given a binary search tree and a node in it, find the in-order successor of that node
in the BST. If the given node has no in-order successor in the tree, return null.
Examples:
Input: root = [2,1,3], p = 1
2
/ \
1 3
Output: 2
Input: root = [5,3,6,2,4,null,null,1], p = 6
5
/ \
3 6
/ \
2 4
/
1
Output: null
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def inorderSuccessor(root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
if not root or not p: return None
if root.val > p.val:
return inorderSuccessor(root.left, p) or root
return inorderSuccessor(root.right, p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment