Created
March 9, 2013 19:11
-
-
Save guolinaileen/5125340 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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