From :https://leetcode.com/problems/recover-binary-search-tree/
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?
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
例如: 中序遍历为1,2,3,4,5,6,7,8,。那么任意调换两个节点,必然大的在前,小的在后。
那么只要找出第一个反序的大的和第二个反序的小的,将两个值交换即可。 但细节上需注意,如果是中序遍历的相邻两个数调换,那么序列中将只有一个逆序对,这时候前一个为大,后一个为小。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode small, large, pre;
public void recoverTree(TreeNode root) {
if(null == root) {
return;
}
find(root);
if(null != small) {
swap();
}
}
private void find(TreeNode root) {
if(null == root) {
return;
}
find(root.left);
if(null != pre && pre.val > root.val) {
small = root;
if(null == large) {
large = pre;
} else {
return;
}
}
pre = root;
find(root.right);
}
private void swap() {
int t = small.val;
small.val = large.val;
large.val = t;
}
}
下面是美丽的师姐的代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void recoverTree(TreeNode root) {
TreeNode pre = null;
TreeNode first = null, second = null;
// Morris Traversal
TreeNode temp = null;
while (root != null) {
if (root.left != null) {
// connect threading for root
temp = root.left;
while (temp.right != null && temp.right != root)
temp = temp.right;
// the threading already exists
if (temp.right != null) {
if (pre != null && pre.val > root.val) {
if (first == null) {
first = pre;
second = root;
} else {
second = root;
}
}
pre = root;
temp.right = null;
root = root.right;
} else {
// construct the threading
temp.right = root;
root = root.left;
}
} else {
if (pre != null && pre.val > root.val) {
if (first == null) {
first = pre;
second = root;
} else {
second = root;
}
}
pre = root;
root = root.right;
}
}
// swap two node values;
if (first != null && second != null) {
int t = first.val;
first.val = second.val;
second.val = t;
}
}
}
本文介绍了一种在不改变二叉搜索树结构的情况下,通过中序遍历找到并修复被错误交换的两个节点的方法。利用中序遍历的有序特性,能够有效地定位问题节点,并进行值的交换来恢复树的正确状态。
3349

被折叠的 条评论
为什么被折叠?



