代码改变世界

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

2018-07-24 01:09  Johnson_强生仔仔  阅读(227)  评论(0编辑  收藏  举报

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
1) S: O(n)
class Solution(object):
    def inorderSuccessor(self, root, p):
        """
        :type root: TreeNode
        :type p: TreeNode
        :rtype: TreeNode
        """
        stack, pre = [], None
        while stack or root:
            if root:
                stack.append(root)
                root = root.left
            else:
                node = stack.pop()
                if pre and pre == p:
                    return node
                pre = node
                root = node.right

 



2) S: O(1)
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