首页 > 代码库 > Leetcode 树 Unique Binary Search TreesII

Leetcode 树 Unique Binary Search TreesII

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Unique Binary Search Trees II

 Total Accepted: 7349 Total Submissions: 27648

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.




题意:给定数字n,生成以数字1到n为节点的二叉查找树

思路:dfs暴力枚举 
以i为根的树的左右树分别是[1,i-1]和[i+1,n]
递归函数:
vector<TreeNode *> generateTree(int begin, int end)
表示生成以[begin,end]的值为节点的二叉查找树

复杂度:不懂分析 

相关题目:Unique Binary Search Trees

/**
 * 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 begin, int end){
    	vector<TreeNode *> results;
    	if(begin > end){
    		results.push_back(NULL);
    		return results;
    	}
    
    	for(int i = begin; i <= end; i++){
    		vector<TreeNode *> left_trees = generateTrees(begin, i - 1);
    		vector<TreeNode *> right_trees = generateTrees(i + 1, end);
    		for(int l = 0; l < left_trees.size(); l++){
    			for(int r = 0; r < right_trees.size(); r++){
    				TreeNode *head = new TreeNode(i);
    				head->left = left_trees[l];
    				head->right = right_trees[r];
    				results.push_back(head);
    			}
    		}
    	}
    
    }
    
    
    vector<TreeNode *> generateTrees(int n){
    	return generateTrees(1, n);
    }
};