您的位置:首页 > 其它

Recover Binary Search Tree:使用常数空间复原二叉搜索树

2017-12-24 20:50 423 查看
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?
思路:题目要求使用常量空间回复二叉树,如果没有这个要求,递归的中序遍历就可以(递归的时候需要栈,空间不是常亮的)。但是Leetcode里的高票答案采用的这一方法,我表示不是很理解。

所以我采用的方法是morris遍历(线索二叉树)+记录中序下位置不符合搜索树的两个节点,记录下值即可。关于不符合位置的点,其可能最多为两对,最少为一对,所以取其中最大者与最小者即为需要交换的点。(可能这里复杂了,需要优化)。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void morris(TreeNode n) {
TreeNode[] res = new TreeNode[2];// _0 : min,_1:max
TreeNode front = null, back = null;
TreeNode cur = n;
TreeNode pre = null;

while (cur != null) {
if (cur.left == null) {
// print(cur);
System.out.println(cur.val);
front = back;
back = cur;
//System.out.println("front,back "+front+" , "+back);
if (front != null && back != null) {
if (front.val >= back.val) {
res[0] = (res[0] == null) ? back : ((back.val < res[0].val) ? back : res[0]);
res[1] = (res[1] == null) ? front : ((front.val > res[1].val) ? front : res[1]);
}
}
cur = cur.right;
} else {
pre = cur.left;
while (pre.right != null && pre.right != cur)
pre = pre.right;
if (pre.right == null) {
pre.right = cur;
cur = cur.left;
} else {
4000
// print(cur)
front = back;
back = cur;
//System.out.println("front,back "+front.val+" , "+back.val);
if (front != null && back != null) {
if (front.val >= back.val) {
res[0] = (res[0] == null) ? back : ((back.val < res[0].val) ? back : res[0]);
res[1] = (res[1] == null) ? front : ((front.val > res[1].val) ? front : res[1]);
}
}
pre.right = null;
System.out.println(cur.val);
cur = cur.right;
}
}
}
int temp = res[0].val;
res[0].val = res[1].val;
res[1].val = temp;
}

public void recoverTree(TreeNode root) {
morris(root);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: