难度困难315收藏分享切换为英文关注反馈
二叉搜索树中的两个节点被错误地交换。
请在不改变其结构的情况下,恢复这棵树。
示例 1:
输入: [1,3,null,null,2]
1
/
3
\
2
输出: [3,1,null,null,2]
3
/
1
\
2
示例 2:
输入: [3,1,4,null,null,2]
3
/ \
1 4
/
2
输出: [2,1,4,null,null,3]
2
/ \
1 4
/
3
进阶:
- 使用 O(n) 空间复杂度的解法很容易实现。
- 你能想出一个只使用常数空间的解决方案吗?
由于二叉搜索树的中序遍历是有序序列,因此在中序遍历中找到至多两对逆序对,交换节点值即可。(只有一对逆序则直接交换那俩节点)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution():
def recoverTree(self, root):
stack = []
pre = None #存储当前节点的上一个节点
x = None
y = None
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop() #取最左
if pre and pre.val>root.val:
y = root
if x == None:
x = pre
pre = root
root = root.right
x.val, y.val = y.val, x.val