题目
分析
二叉搜索树的中序遍历就是递增序列,所以我们只要找到被替换树的中序过程中违反递增规律的节点就可以了。
替换后 有两种情况:
1,[1,3,2,4]
2, [4,2,3,1]
第一种情况 替换3和2的值。
第二种情况 替换4和1的值。
在中序遍历树的过程中,只要我们发现逆序数对并且用两个值x,y记录逆序数对的两个值。
在第一种情况下 x,y被同时赋值。
在第二种情况下,先记录x=4,后记录y=1。
最后替换x,y的值,完成恢复。
python代码
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
x,y = None,None
stack = []
pre = None
while root or stack:
while root:
stack.append(root)
root = root.left
if stack:
t = stack.pop(-1)
if pre and pre.val > t.val:
y = t
if not x:
x = pre
else:
break
pre = t
root = t.right
x.val,y.val = y.val,x.val