Friday, July 25, 2014

Unique Binary Search Tree ii

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
Algorithm:
This problem is solved using recursion. We should know that every number between 1 and n can be a root value. Thus, going from 1 to n, each time get a number i as the root, the numbers smaller than i form the left child tree and the numbers larger than i form the right child tree. Recursively do this.

Code:

 public class Solution {  
   public List<TreeNode> generateTrees(int n) {  
     return helper(1, n);  
   }  
   public List<TreeNode> helper(int begin, int end) {  
     List<TreeNode> list = new ArrayList<TreeNode>();  
     if (begin > end) {  
       list.add(null);  
       return list;  
     }  
     for (int i=begin; i<=end; i++) {  
       List<TreeNode> left = helper(begin, i-1);  
       List<TreeNode> right = helper(i+1, end);  
       for (int j=0; j<left.size(); j++) {  
         for (int k=0; k<right.size(); k++) {  
           TreeNode root = new TreeNode(i);  
           root.left = left.get(j);  
           root.right = right.get(k);  
           list.add(root);  
         }  
       }  
     }  
     return list;  
   }  
 }  

NOTE: for one value, there is probably several structurally unique binary trees, like 3 as root in the example

No comments:

Post a Comment