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.
/**
* 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 pre;
private TreeNode first;
private TreeNode second;
public void inorder(TreeNode root){
if (root == null) {
return;
}
inorder(root.left);
if (pre == null) {
pre = root;
} else {
if (pre.val >= root.val) {
if (first == null) {
first = pre;
}
second = root;
}
pre = root;
}
inorder(root.right);
}
public void recoverTree(TreeNode root) {
inorder(root);
if (first!=null && second!=null) {
int tmp = first.val;
first.val = second.val;
second.val = tmp;
}
}
}
本文详细介绍了如何在不改变二叉搜索树结构的情况下,解决树中两个元素位置错误的问题,提供了使用常数空间复杂度的解决方案,并解释了序列化和反序列化二叉树的概念。
322

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



