099 Recover Binary Search Tree

099 Recover Binary Search Tree

没有按照要求用 constant space.... 用valid BST 找出两个not in order 的nodes

class Solution:
    def recoverTree(self, root):
        [fN, sN] = self.valid(root)
        fN.val, sN.val = sN.val, fN.val

    def valid(self, root):
        pre, fN, sN = TreeNode(-100000), None, None
        stack = []
        while True:
            while root != None:
                stack.append(root)
                root = root.left
            if stack == []:
                break
            root = stack.pop()
            if pre.val >= root.val:
                if not fN:
                    fN = pre
                    sN = root
                else:
                    sN = root
                    break
            pre = root
            root = root.right
        return [fN, sN]

 

posted @ 2015-08-06 05:25  dapanshe  阅读(107)  评论(0编辑  收藏  举报