Unique Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
Unique Binary Search TreesII
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
分析:这个题目是要求BST有多少种排列方式,第一题是只求数量,第二题要求把结构也存储下来。本质都是深搜,第一题显然更简单
因为只要知道当前有多少个数,就可以知道有多少种排列方式了,甚至可以简单的建个存储表,更快一些。而第二题就需要将当前情况
下所有点的排列搞到,返回上一级,上一级再建立更高一层的bst
第一题代码:
class Solution { public: int numTrees(int n) { if(n==0) return 1; if(n==1) return 1; int wnum = 0; for(int i=1;i<=n;i++) { wnum += numTrees(i-1) * numTrees(n-i); } return wnum; } };
第二题代码:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<TreeNode *>builtree(int left,int right) 13 { 14 vector<TreeNode *>data; 15 if(left>right) 16 { 17 data.push_back(nullptr); 18 return data; 19 } 20 21 vector<TreeNode *>leftr,rightr; 22 for(int i=left;i<=right;i++) 23 { 24 25 leftr = builtree(left,i-1); 26 rightr = builtree(i+1,right); 27 for(int t1=0;t1<leftr.size();t1++) 28 for(int t2=0;t2<rightr.size();t2++) 29 { 30 TreeNode *nod = new TreeNode(i); 31 nod->left = leftr[t1]; 32 nod->right = rightr[t2]; 33 data.push_back(nod); 34 } 35 } 36 return data; 37 38 } 39 vector<TreeNode *> generateTrees(int n) { 40 vector<TreeNode *> data(1,nullptr); 41 data = builtree(1,n); 42 return data; 43 } 44 };
来源:https://www.cnblogs.com/soyscut/p/3783558.html