Recover Binary Search Tree

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

Recover the tree without changing its structure.

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

要求找到BST中放错位置的两个节点.

直观思路是使用中序遍历来解.一颗正常的BST,它的正常中序遍历序列是递增序列(非递减,如果有重复元素).所以如果有元素被交换,则会出现递减的情况.如果不是前后继的两个节点,则只会出现一次颠倒的情况,而如果不是前后继,则会出现两次,举例如下:

1 2 3 4 5 6 7这是一个正常的BST中序遍历序列.如果是前后继的两个节点,比如3,4交换,则中序遍历序列是: 1 2 4 3 5 6 7. 4 3出现一次逆序. 如果不是前后继,比如3,5交换,则中序遍历为1 2 5 4 3 6 7. 则5 4, 4 3是两次逆序.可以看出在第一个逆序对里前面一个值是第一个逆序节点.而在后一个逆序对里后一个值是逆序节点. 而在仅有一个逆序对的情况下,前一个值为第一个逆序节点,后一个值为第二个逆序节点. 时间复杂度为O(n).空间复杂度为O(nlogn).代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def recoverTree(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        if not root:
            return
        stack = []
        prev = TreeNode(-sys.maxint-1)
        cur = root
        former = None
        latter = None
        while stack or cur:
            if cur:
                stack.append(cur)
                cur = cur.left
            else:
                cur = stack.pop()
                if cur.val < prev.val:
                    if not former:
                        former = prev
                        latter = cur
                        prev = cur
                    else:
                        latter = cur
                        break
                else:
                    prev = cur
                cur = cur.right
        former.val, latter.val = latter.val, former.val

题目要求的O(1)空间复杂度需要结合morris遍历来做, 详见http://www.cnblogs.com/AnnieKim/archive/2013/06/15/morristraversal.html

posted on 2016-07-11 17:12  Sheryl Wang  阅读(129)  评论(0编辑  收藏  举报

导航