Leetcode - Recover Binary Search Tree

6 篇文章 0 订阅
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,其中序遍历序列是一个递增序列,假设A,B节点互换了位置,则在中序遍历中A比其后元素大,B比前面元素小,可据此性质找出AB节点并调换回来。


/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// Method 2: recursive
TreeNode prev, p, q;
public void recoverTree(TreeNode root) {
inorder(root);
if (p != null) {
int tmp = p.val;
p.val = q.val;
q.val = tmp;
}
}
public void inorder(TreeNode root) {
if (root == null) return;
inorder(root.left);
if (prev != null && prev.val > root.val) {
if (p == null)
p = prev;
q = root;
}
prev = root;
inorder(root.right);
}

// Method 1: iterative
public void recoverTree1(TreeNode root) {
if (root == null) return;
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
TreeNode curr = root, prev = null;
TreeNode errPair1First = null, errPair1Sec = null;
TreeNode errPair2Sec = null;
while (!stack.isEmpty() || curr != null) {
if (curr != null) {
stack.push(curr);
curr = curr.left;
} else {
curr = stack.pop();
if (prev != null && prev.val > curr.val) {
if (errPair1First == null) {
errPair1First = prev;
errPair1Sec = curr;
} else {
errPair2Sec = curr;
break;
}
}
prev = curr;

curr = curr.right;
}
}
if (errPair2Sec == null) {
swap(errPair1First, errPair1Sec);
} else {
swap(errPair1First, errPair2Sec);
}
}
private void swap (TreeNode node1, TreeNode node2) {
int tmp = node1.val;
node1.val = node2.val;
node2.val = tmp;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值