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:
    vector<TreeNode*> generateTrees(int n) {
        vector<TreeNode*> result;
	    vector<vector<vector<TreeNode*> > > buf(n, vector<vector<TreeNode*> >(n));
	    visit(1, n, result, buf);

	    return result;
    }
    
private:
    void visit(int begin, int end, vector<TreeNode*> &result, vector<vector<vector<TreeNode*> > > &buf)
    {
	    if (begin > end)
	    {
		    result.push_back(NULL);
		    return;
	    }

	    if (!buf[begin-1][end-1].empty())
	    {
		    result = buf[begin-1][end-1];
		    return;
	    }

	    for (int i = begin; i <= end; i++)
	    {
		    vector<TreeNode*> left, right;
		    visit(begin, i-1, left, buf);
		    visit(i+1, end, right, buf);

		    for (int j = 0; j < left.size(); j++)
		    {
			    for (int k = 0; k < right.size(); k++)
			    {
				    TreeNode *temp = new TreeNode(i);
				    temp->left = left[j];
				    temp->right = right[k];
				    result.push_back(temp);
			    }
		    }
	    }

	    buf[begin-1][end-1] = result;
    }
};


你可能感兴趣的:(Unique Binary Search Trees II)