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有一个性质,就是它的中序遍历是有序的,可以根据这个性质来做~要注意考虑有两种情况:如果是相邻的节点被调换了,那么就只出现一次逆序;如果调换的两个节点不相邻,就会出现两次逆序;用first, second来记录两个交换了的节点;
下面代码是根据中序遍历的非递归解法写的~这种解法时间复杂度为O(n),空间复杂度为O(logn)~
class Solution:
# @param root, a tree node
# @return a tree node
def recoverTree(self, root):
if root is None: return None
pre, first, second, stack, cur = None, None, None, [], root
while stack or cur:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
if pre and pre.val > cur.val:
if first is None:
first, second = pre, cur
else:
second = cur
pre, cur = cur, cur.right
first.val, second.val = second.val, first.val
return root