Skip to content

285. Inorder Successor in BST

难度: 中等

刷题内容

原题连接

  • https://leetcode.com/problems/inorder-successor-in-bst

内容描述


Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return null.

Example 1:

Input: root = [2,1,3], p = 1

  2
 / \
1   3

Output: 2
Example 2:

Input: root = [5,3,6,2,4,null,null,1], p = 6

      5
     / \
    3   6
   / \
  2   4
 /   
1

Output: null

解题方案

思路 1

首先可以去看一下二叉树的一些操作

BST的特性,对于一个node,它的所有左侧node都比它小,它的所有右侧node都比它大。最小的元素在最左边,最大的元素在最右边。

一个node x它的successor y 是满足y > x的最小值。两种情况,如果node x有right child,那么这个right child 中的最小值就是它的successor,否则就要往上走,如果走上去的parent使得这个node是其左边的孩子的话,那么successor我们也找到了。

因为状况可能是这样的:

        3
      /
     1
   /  \
  0    2

如果是寻找0的successor,那么我们往上一走,发现0的祖先是1,并且0是1的左孩子,找到,否则如果寻找2的successor,那么我们要往上走到3的部分,2是3的左subtree,这样才能解决问题。

伪码

function Succ(x)    
    if Right(x) ̸= NIL then     
        return Min(Right(x))    
    else        
        p ← Parent(x)       
        while p ̸= NIL and x = Right(p) do          
            x←p         
            p ← Parent(p) 
        return p

这里伪码有点不适用是因为我们并没有这个parent指针,当然我们还是有trick方式的,就是我们从root开始走,直到找到这个node p,同时我们记录一路上看到的比p.val大的值,这样最后一个就是它的successor.其中最低的那一个就是他的successor.

class Solution(object):
    def inorderSuccessor(self, root, p):
        """
        :type root: TreeNode
        :type p: TreeNode
        :rtype: TreeNode
        """
        def minNode(node):
            while node.left:
                node = node.left
            return node

        def searchP(root, p):
            if not root or root.val == p.val:
                return None
            else:
                succ = None
                while root != None and p.val != root.val:
                    if p.val < root.val:
                        succ = root
                        root = root.left
                    else:
                        root = root.right
                return succ

        if p.right:
            return minNode(p.right)
        else:
            return searchP(root, p)

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组