[LeetCode] Unique Binary Search Trees II
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.
Tree Dynamic Programming
Have you met this question in a real interview?
Yes
No
思路:Unique Binary Search Trees是用dp,求解所有的trees不能用dp。
对于每一个root,有leftNum * rightNum种情况,直接穷举,对于start>end, 返回含有NULL的一个节点,start==end也返回一个节点,框架和深搜一样
class Solution { public: vector<TreeNode *> dfs(int start, int end) { vector<TreeNode*> trees; if(start > end) { trees.push_back(NULL); return trees; } if(start == end) { TreeNode* p = new TreeNode(start); trees.push_back(p); return trees; } for(int rootVal = start; rootVal <= end; rootVal ++) { vector<TreeNode*> leftSubTrees = dfs(start, rootVal - 1); vector<TreeNode*> rightSubTrees = dfs(rootVal + 1, end); int leftSubTreesNum = leftSubTrees.size(); int rightSubTreesNum = rightSubTrees.size(); for(int i = 0; i < leftSubTreesNum; i++) { for(int j= 0; j< rightSubTreesNum; j++) { TreeNode* root = new TreeNode(rootVal); TreeNode* left = leftSubTrees[i]; TreeNode* right= rightSubTrees[j]; root->left = left; root->right= right; trees.push_back(root); } } } return trees; } vector<TreeNode *> generateTrees(int n) { if(n == 0) { vector<TreeNode *> trees; trees.push_back(NULL); return trees; } return dfs(1, n); } };