Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Created March 9, 2013 19:11
Show Gist options
  • Save guolinaileen/5125340 to your computer and use it in GitHub Desktop.
Save guolinaileen/5125340 to your computer and use it in GitHub Desktop.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode previous;
public void recoverTree(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<TreeNode> list=new ArrayList<TreeNode>();
previous=null;
inOrder(root, list);
int temp=list.get(0).val;
list.get(0).val=list.get(list.size()-1).val;
list.get(list.size()-1).val=temp;
}
void inOrder(TreeNode root, ArrayList<TreeNode> list)
{
if(root==null) return ;
inOrder(root.left, list);
if(previous!=null && previous.val>root.val)
{
if(!list.contains(previous)) list.add(previous);
if(!list.contains(root)) list.add(root);
}
previous=root;
inOrder( root.right, list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment