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?
题意:二叉搜索树中有两个节点的值交换,在不修改二叉树的结构的前提下修正该树
O(n)空间的算法是用中序遍历求出二叉树的现有顺序存在一个新数组中,再进行排序,最后将排序后的值重新赋给原树,这种方法通用n个节点错乱的情况。
O(1)空间算法:中序遍历的过程中用两个指针来找寻混乱的两个节点,思路参考http://blog.csdn.net/havenoidea/article/details/12869021
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode s1=null, s2=null, pre=null;
public void inorder(TreeNode root){
if(root != null){
inorder(root.left);
if(pre!=null && pre.val > root.val){
if(s1 == null){
s1 = pre;//异常的第一个节点
}
s2 = root;//异常的第二个节点
}
pre = root;
inorder(root.right);
}
}
public void recoverTree(TreeNode root) {
inorder(root);
int t = s1.val;
s1.val = s2.val;
s2.val = t;
}
}