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.
这个题目是binary tree iterative in-order traversal的一个应用实例。中序遍历那道题里面写了如何对binary tree进行iterative的中序遍历,主要思想就是用stack来模拟递归。对这道题而言,还需要维护两个指针,pre和cur。当出现pre的值大于cur的值的时候,更新first和second指针的值。这里会有两种情况:
1. 如果是相邻的两个node调换了位置,那么pre大于cur的情况只会出现一次。
2. 如果是不相邻的两个node调换了位置,pre大于cur的情况会出现两次,需要更正的node分别为第一次的pre和第二次的cur。
在遍历结束,或者遍历过程中遇到了两次异常情况之后,对first和second指针所指向的node进行交换即可。
代码如下:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void recoverTree(TreeNode root) {
if(root==null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
boolean flag = false;
TreeNode cur=root, pre=null, first=null, second=null;
while(cur!=null || !stack.isEmpty()) {
while(cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
if(pre == null) {
pre = cur;
}
else {
if(pre.val > cur.val) {
if(!flag) {
first = pre;
second = cur;
flag = true;
}
else {
second = cur;
break;
}
}
pre = cur;
}
cur = cur.right;
}
int temp = first.val;
first.val = second.val;
second.val = temp;
return;
}
}