285. Inorder Successor in BST

Difficulty
Medium
Tags
二叉树
Star
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
The successor of a node p is the node with the smallest key greater than p.val.
Example 1:
notion imagenotion image
Input:root = [2,1,3], p = 1 Output:2 Explanation:1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.
Example 2:
notion imagenotion image
Input:root = [5,3,6,2,4,null,null,1], p = 6 Output:null Explanation:There is no in-order successor of the current node, so the answer isnull.
Note:
  1. If the given node has no in-order successor in the tree, return null.
  1. It's guaranteed that the values of the tree are unique.

法 1 普通二叉树 中序遍历

思路
用prev 来标记 节点 p, 即遍历到p节点的时候,prev = True, 然后继续遍历之后的节点,同时判断prev == True, 如果是,直接返回。
题解
class Solution def inorderSuccessor(root, p): flag = False res = None stack = [] while stack or root: if root: stack.append(root) root = root.left else: root = stack.pop() if flag: res = root break if root is p: flag = True root = root.right return res

法 2 利用 bst的性质

思路
如果根节点的值小于或等于P节点的值,则意味着p的后继节点必须位于右子树中,因此在右子节点上递归地调用该函数。
如果根节点的值大于P的值,则根节点可能是P的继承者,或者左子树中的节点是P的继承者,*首先递归调用此功能左子节点,如果它返回空,指示根节点是继承人节点,刚返回,如果它不为空,则返回该节点
题解
class Solution def inorderSuccessor(root, p): if root is None: return None # 说明后继节点一定在右子树上 if root.val <= p.val: return self.inorderSuccessor(root.right, p) # 说明后继节点在左子树上, 且当前节点可能就是结果 # if left is None 说明p就是当前节点左子树上的最大值, 所以当前节点 即为后继 # 如果 left 存在, 那就是left了 else: left = self.inorderSuccessor(root.left, p) return left if left else root