首页 > 其他 > 详细

Leetcode 树 Unique Binary Search TreesII

时间:2014-05-15 07:02:14      阅读:398      评论:0      收藏:0      [点我收藏+]

本文为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);
    }
};


Leetcode 树 Unique Binary Search TreesII,布布扣,bubuko.com

Leetcode 树 Unique Binary Search TreesII

原文:http://blog.csdn.net/zhengsenlie/article/details/25657649

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!