首页 > 代码库 > 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: 27648Given 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); } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。