如果结点 p 的值大于等于 root 的值,说明 p 的后继结点在 root 右子树中,那么就递归到右子树中查找
如果结点 p 的值小于 root 的值,说明 p 在 root 左子树中,而它的后继结点有两种可能,要么也在左子树中,要么就是 root
如果左子树中找到了后继结点,那就直接返回答案
如果左子树中没有找到后继结点,那就说明 p 的右儿子为空,那么 root 就是它的后继结点
搜索的过程可以分为递归和非递归两种方式.
递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
if root is None:
return
if p.val >= root.val:
return self.inorderSuccessor(root.right, p)
else:
node = self.inorderSuccessor(root.left, p)
return root if node is None else node
非递归
class Solution:
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
# 首先向右查找, 如果有右子树, 结果肯定在这里面
if p.right is not None:
current = p.right
while current is not None and current.left is not None:
current = current.left
return current
# 右子树中没有, 从根节点出发, 寻找`p`结点的位置
stack = []
current = root
while current is not p:
stack.append(current)
current = current.right if p.val > current.val else current.left
while stack and stack[-1].left is not current:
current = stack.pop(-1)
if stack:
return stack[-1]
return None