边工作边刷题:70天一遍leetcode: day 18

Recover Binary Search Tree

要点:如果两个交换,那么会有两对顺序相反,或者如果是相邻的交换,那么仅有一对。所以第一次发现逆序更新first和second,第二次只更新second

  • in order traversal如何track prev?其实和bst找第k个或者前一个都是一个pattern。就是先递归向左,返回后,prev已经更新。然后root变prev,然后递归向右
  • 因为python是pass-by-value的,所以prev只能用全局变量,而不能pass around。也不需要返回

python实现中的问题:

  • 首先first和second是global的,在python里,nested function可以读enclosing的变量,但是不能update(update就变成对local变量操作)。所以这题把变量弄成class member
# 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 _recover(self, root):
        if not root:
            return 

        if root.left:
            self._recover(root.left)
        # print root.val,self.prev
        if self.prev and root.val<self.prev.val:
            if self.first is None:
              self.first = self.prev
            self.second = root
        self.prev = root
        # print self.prev
        if root.right:
            self._recover(root.right)
    
    def recoverTree(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        self.first = None
        self.second = None
        self.prev = None
        
        self._recover(root)
        self.first.val, self.second.val = self.second.val, self.first.val
            
        
posted @ 2016-05-02 09:36  absolute100  阅读(107)  评论(0编辑  收藏  举报