wo elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure. Constant extra space.
[code]
public class Solution {
TreeNode node1, node2, prev;
public void recoverTree(TreeNode root) {
if(root==null)return;
if(root.left==null && root.right==null)return;
node1=null;
node2=null;
prev=null;
helper(root);
int temp=node1.val;
node1.val=node2.val;
node2.val=temp;
}
void helper(TreeNode node)
{
if(node==null)return;
helper(node.left);
if(prev!=null && node.val<prev.val)
{
if(node1==null)
{
node1=prev;
}
node2=node;
}
prev=node;
helper(node.right);
}
}
[Thoughts]
很容易忽略两个nodes相邻的情况