Sunday, February 1, 2015

95 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 binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<TreeNode *> generateTrees(int n) {
        vector<TreeNode*> res;
        help(1,n,res);
        return res;
    }
    void help(int first,int last,vector<TreeNode*>& res)
    {
        if (first>last)
        {
            res.push_back(NULL);
            return;
        }
        for (int i=first;i<=last;i++)
        {
            vector<TreeNode*> leftChild,rightChild;
            help(first,i-1,leftChild);
            help(i+1,last,rightChild);
            for (int j=0;j<leftChild.size();j++)
            {
                for (int k=0;k<rightChild.size();k++)
                {
                    TreeNode* root = new TreeNode(i);
                    root->left = leftChild[j];
                    root->right = rightChild[k];
                    res.push_back(root);
                }
            }
        }
    }
};

No comments:

Post a Comment