In a binary search tree, (Only) two nodes are swapped. Find out these nodes and swap them. If there no node swapped, return original root of tree.Have you met this question in a real interview? Yes
Example
Given a binary search tree:
4
/ \
5 2
/ \
1 3
return
4
/ \
2 5
/ \
1 3
Based on inorder traversal. O(N)
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the given tree
* @return: the tree after swapping
*/
public TreeNode first = null;
public TreeNode second = null;
public TreeNode last = new TreeNode(Integer.MIN_VALUE);
public TreeNode bstSwappedNode(TreeNode root) {
// write your code here
if(root == null){
return null;
}
traversal(root);
if(first != null && second != null){
int tmp = first.val;
first.val = second.val;
second.val = tmp;
}
return root;
}
public void traversal(TreeNode root){
if(root == null){
return;
}
traversal(root.left);
if(first == null && root.val < last.val){
first = last;
}
if(first != null && root.val < last.val){
second = root;
}
last = root;
traversal(root.right);
}
}