Friday, January 16, 2015

Unique Binary Search Trees II (LeetCode Tree)

Question: Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.


   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
Idea: Brute force recursion. Use every number  i as root, its left tree is (start,..., i-1) , its right tree is (i+1,...,end).

Time: O(n^2) Space: O(n)

Code:
 public class Solution {  
   public List<TreeNode> generateTrees(int n) {  
     return generate(1,n);  
   }  
   public List<TreeNode> generate(int start,int end)  
   {  
     List<TreeNode> result=new ArrayList<TreeNode>();  
     if(start>end)  
     {    
       result.add(null);  
       return result;  
     }  
     for(int i=start;i<=end;i++)  
     {  
       List<TreeNode> leftNode=generate(start,i-1);  
       List<TreeNode> rightNode=generate(i+1,end);  
       for(TreeNode l:leftNode)  
       {  
         for(TreeNode r:rightNode)  
         {  
           TreeNode cur=new TreeNode(i);  
           cur.left=l;  
           cur.right=r;  
           result.add(cur);  
         }  
       }  
     }  
     return result;  
   }  
 }  

No comments:

Post a Comment