LeetCode面试题 04.06. 后继者

LeetCode面试题 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:

        ans = None
        if p.right:
            ans = p.right
            while ans.left: ans = ans.left
            return ans
        else:
            cur = root
            while cur:
                if cur.val > p.val: ans, cur = cur, cur.left
                else: cur = cur.right
            
            return ans

posted on 2022-07-01 18:49  solvit  阅读(17)  评论(0编辑  收藏  举报

导航