给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。
进阶:使用 O(n) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗?
方法一:中序遍历+指针
- 用中序遍历的方式遍历这颗二叉搜索树,我们增加一个辅助的pre指针,记录 上一个 节点的值。
- 如果 当前节点的值,小于 上一个节点的值,这就找到了需要交换的节点。利用这种方式,就不需要额外的数组空间了。
class Solution {
//用两个变量x,y来记录需要交换的节点
private TreeNode x = null;
private TreeNode y = null;
private TreeNode pre = null;
public void recoverTree(TreeNode root) {
dfs(root);
//如果x和y都不为空,说明二叉搜索树出现错误的节点,将其交换
if(x!=null && y!=null) {
int tmp = x.val;
x.val = y.val;
y.val = tmp;
}
}
//中序遍历二叉树,并比较上一个节点(pre)和当前节点的值,如果pre的值大于当前节点值,则记录下这两个节点
private void dfs(TreeNode node) {
if(node==null) {
return;
}
dfs(node.left);
if(pre==null) {
pre = node;
}
else {
if(pre.val>node.val) {
y = node;
if(x==null) {
x = pre;
}
}
pre = node;
}
dfs(node.right);
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/recover-binary-search-tree