面试题 04.06. 后继者

exiaohu 于 2022-05-16 发布

题目链接:面试题 04.06. 后继者

使用迭代方式中需遍历。

# 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 | None:
        stack, cur, visited = [], root, False

        while stack or cur:
            while cur:
                stack.append(cur)
                cur = cur.left

            cur = stack.pop()
            if visited:
                return cur

            if id(cur) == id(p):
                visited = True

            cur = cur.right

        return None