[leetcode] 285. Inorder Successor in BST

208 阅读1分钟

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

The successor of a node p is the node with the smallest key greater than p.val

` 方案一: 找出所有节点

# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def inorderSuccessor(self, root, p):
        """
        :type root: TreeNode
        :type p: TreeNode
        :rtype: TreeNode
        """
        l = []

        def inOrder(root):
            if not root:
                return
            inOrder(root.left)
            l.append(root.val)
            inOrder(root.right)

        inOrder(root)
        i = l.index(p.val)
        return TreeNode(l[i + 1]) if i < len(l) - 1 else None

方案二: 二分查找

# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def inorderSuccessor(self, root, p):
        """
        :type root: TreeNode
        :type p: TreeNode
        :rtype: TreeNode
        """
        result = None
        while root:
            if root.val < p.val:
                result = root
                root = root.left
            else:
                root = root.right
        return result

`