Thursday, January 15, 2015

Recover Binary Search Tree (LeetCode Tree)

Question: Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.

Idea: In order traversal, use two class member variables to record the two abnormal nodes. Then swap their values.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   TreeNode v1,v2,prev;  
   public void recoverTree(TreeNode root) {  
     v1=null;  
     v2=null;  
     prev=new TreeNode(Integer.MIN_VALUE);  
     traversal(root);  
     int tmp=v1.val;  
     v1.val=v2.val;  
     v2.val=tmp;  
   }  
   public void traversal(TreeNode root)  
   {  
     if(root==null)  
       return;  
     traversal(root.left);  
     if(v1==null&&prev.val>=root.val)  
       v1=prev;  
     if(v1!=null&&prev.val>=root.val)  
       v2=root;  
     prev=root;  
     traversal(root.right);  
   }  
 }  

No comments:

Post a Comment