[LeetCode] 285. Inorder Successor in BST_Medium tag: Inorder Traversal

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

这个题目思路可以用recursive方式, 去将tree换为sorted list, 然后找到p的下一个元素即可. T: O(n) S: O(n)
但是我们可以用T: O(h) S: O(1) iterable的方式, 类似于去找p, 然后给p的下一个元素即可.

code
class Solution:
    def inorderSuccessor(self, root, p):
        ans = None
        while root:
            if root.val > p.val:
                ans = root
                root = root.left
            else:
                root = root.right
        return ans


猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9357797.html