99.Recover Binary Search Tree

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?
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def recoverTree(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        if root is None:
            return None
        list = []
        def preorder(root):
            list.append(root.val)
            if root.left:
                preorder(root.left)
            if root.right:
                preorder(root.right)
        preorder(root)
        list.sort()
        pos = 0
        def inorder(root):
            nonlocal pos
            if root.left:
                inorder(root.left)
            root.val = list[pos]
            pos += 1
            if root.right:
                inorder(root.right)
        inorder(root)
        return
posted @ 2018-11-30 15:14  bernieloveslife  阅读(123)  评论(0编辑  收藏  举报