[面试题 04.06][中等][DFS] 后继者
题目描述
输入: root = [2,1,3], p = 1
2
/ \
1 3
输出: 2输入: root = [5,3,6,2,4,null,null,1], p = 6
5
/ \
3 6
/ \
2 4
/
1
输出: null解题思路

最后更新于
输入: root = [2,1,3], p = 1
2
/ \
1 3
输出: 2输入: root = [5,3,6,2,4,null,null,1], p = 6
5
/ \
3 6
/ \
2 4
/
1
输出: null
最后更新于
# 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 nodeclass 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