码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Unique Binary Search Trees II

时间:2015-01-14 09:52:27      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:leetcode   bst   递归   

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

/**
 * 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) 
	{
		return generateTrees(1,n);
    }
	vector<TreeNode*> generateTrees(int s, int e)
	{
		vector<TreeNode*> res;
		if(s > e)
		{
			res.push_back(NULL);
			return res;
		}
		if(s == e)
		{
			TreeNode* t = new TreeNode(s);
			res.push_back(t);
			return res;
		}
		for(int i=s; i<=e; i++)
		{
			vector<TreeNode*> left = generateTrees(s,i-1);
			vector<TreeNode*> right = generateTrees(i+1,e);
			for(int p=0; p<left.size(); p++)
			{
				for(int q=0; q<right.size(); q++)
				{
					TreeNode* t = new TreeNode(i);
					t->left = left[p];
					t->right = right[q];
					res.push_back(t);
				}
			}
		}
		return res;
	}
};


LeetCode--Unique Binary Search Trees II

标签:leetcode   bst   递归   

原文地址:http://blog.csdn.net/shaya118/article/details/42689539

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!