代码改变世界

[LeetCode] 99. Recover Binary Search Tree_Hard_Inorder traversal

2018-08-07 23:37  Johnson_强生仔仔  阅读(198)  评论(0编辑  收藏  举报

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

Follow up:

  • A solution using O(n) space is pretty straight forward.
  • Could you devise a constant space solution?

 

因为是BST, 所以需要用到inorder traversal来判断是哪两个点需要交换, 因此, 我们用pre来记录之前遍历的node, 然后第一个pre.val > node.val, 表明pre为第一个不对的node, node 可能为第二个点,

然后通过同样的道理, 如果第一个找到了, 我们就不断通过pre.val > node.val 这一条件将node更新为第二个点.最后将第一个点和第二个点交换, 即可.

 

1. Constriants

1) None => Nothing

 

2. Ideas

Inorder traversal     T; O(n)     S; O(1)

 

3. Code

class Solution:
    def recoverBST(self, root):
        ans = [None, None, None]  #firNode, secNode, pre
        def helper(node, ans):
            if not node: return 
            helper(node.left, ans)
            if not ans[0] and ans[2] and ans[2].val > node.val:
                ans[0] = ans[2]
          ans[1] = node el
if ans[0] and ans[2].val > node.val: ans[1] = node ans[2] = node helper(node.right, ans) helper(root, ans) ans[0].val, ans[1].val = ans[1].val, ans[0].val

2) iterable

class Solution(object):
    def recoverTree(self, root):
        """
        :type root: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        ans = [None, None, None] # first, second, pre
        stack = []
        while stack or root:
            if root: 
                stack.append(root)
                root = root.left
            else:
                node = stack.pop()
                if not ans[0] and ans[2] and ans[2].val >= node.val:
                    ans[0] = ans[2]
                    ans[1] = node
                elif ans[0] and ans[2].val >= node.val:
                    ans[1] = node
                ans[2] = node
                root = node.right
        ans[0].val, ans[1].val = ans[1].val, ans[0].val

 

4. Test cases

1) 

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3