Longest Consecutive Sequence @ LeetCode (Python)
Plus One @ LeetCode (Python)

Recover Binary Search Tree @ LeetCode (Python)

kitt posted @ 2014年2月19日 20:46 in LeetCode , 2268 阅读

BST中序遍历就是一个sorted list, 要求O(1) space, 经1楼提醒, 用first, second两个变量记录可能交换的节点即可。如果只有一个降序对(如20, 10, 30, 40, 50), 用first, second记录。如果有两个降序对(如10, 40, 30, 20, 50或50, 20, 30, 40, 10), 用第二个降序对中小的数更新second。while循环中19~23行换成"print root.val"就是非递归的中序遍历。

 

The result of BST inorder traversal is a sorted list. This problem requires O(1) space, according to the first comment below, only two variables (first, second) are enough to record nodes to be exchanged. If there's only one descending order pair (e.g. 20, 10, 30, 40, 50), use first & second to record it. If there are two descending order pairs (e.g. 10, 40, 30, 20, 50 or 50, 20, 30, 40, 10), use the smaller number in second pair to update second. If we change line 19-23 in while loop to "print root.val", then it's non-recursive inorder traversal of binary tree.

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a tree node
    def recoverTree(self, root):
        originalRoot, stack = root, []
        prev = first = second = None
        while stack or root:
            if root:
                stack.append(root)
                root = root.left
            else:
                root = stack.pop()
                if prev and root.val < prev.val:
                    if first == None:
                        first, second = prev, root
                    else:
                        second = root
                prev, root = root, root.right
        first.val, second.val = second.val, first.val
        return originalRoot
Avatar_small
有问题 说:
2014年4月05日 03:00

根据starforever的解法,只需要两个指针
第一次遇到逆序记录prev和cur
如果第二次遇到逆序只记录cur
最后swap prev和cur
事后分析,第一次可以检测到逆序是在逆序发生地的后一个位置,所以保存prev(大数在前面不会判错)
第二次可以检测到的话那就是当前了(小数在后面可以马上发现错误)。

https://github.com/starforever/leet-code/blob/master/Recover%20Binary%20Search%20Tree/Solution.java

Avatar_small
kitt 说:
2014年4月07日 17:09

@有问题: 犀利!thx~


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter