Saturday, May 2, 2015

[LeetCode] Unique Binary Search Trees 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
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void generate(vector<TreeNode*> &res, int num, int offset)
    {
        if(0 == num) 
        {
            res.push_back(NULL);
            return;
        }
        if(1 == num)
        {
            TreeNode* node = new TreeNode(num+offset);
            res.push_back(node);
            return;
        }
        for(int i=1;i<=num;i++)
        {
            vector<TreeNode*> left, right;
            generate(left, i - 1, offset);
            generate(right, num - i, offset + i );
            
            for(int j=0;j<left.size();j++)
            {
                for(int k=0;k<right.size();k++)
                {
                    TreeNode *cur = new TreeNode(i+offset);
                    cur->left = left[j];
                    cur->right = right[k];
                    res.push_back(cur);
                }
            }
        }
        
    }
    vector<TreeNode*> generateTrees(int n) {
        vector<TreeNode*> res;
        generate(res, n, 0);
        return res;
    }
};