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?
思路:inorder travel; 注意第一次 pre > cur, 的时候,要记录两个值,然后第二次pre > cur的时候就cur值就好了;
注意传参数是传array,或者用全局变量;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void recoverTree(TreeNode root) {
TreeNode[] res = new TreeNode[] {null, null};
InOrderTraverse(root, res);
}
private void InOrderTraverse(TreeNode root, TreeNode[] res) {
Stack<TreeNode> stack = new Stack<>();
pushLeft(root, stack);
TreeNode pre = null;
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
if(pre == null) {
pre = node;
} else {
if(pre.val > node.val) {
if(res[0] == null) {
res[0] = pre;
res[1] = node;
} else {
res[1] = node;
break;
}
}
pre = node;
}
if(node.right != null) {
pushLeft(node.right, stack);
}
}
// swap res[0] & res[1];
int temp = res[0].val;
res[0].val = res[1].val;
res[1].val = temp;
}
private void pushLeft(TreeNode node, Stack<TreeNode> stack) {
while(node != null) {
stack.push(node);
node = node.left;
}
}
}