题目:
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
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode*> generateTrees(int n) { return Solution::generateBST(1, n); } static vector<TreeNode*> generateBST(int min, int max) { vector<TreeNode*> ret; if ( min>max ) { ret.push_back(NULL); return ret; } for ( int i = min; i<=max; ++i ) { vector<TreeNode*> left = Solution::generateBST(min, i-1); vector<TreeNode*> right = Solution::generateBST(i+1,max); for ( size_t l = 0; l < left.size(); ++l ) { for ( size_t r = 0; r < right.size(); ++r ) { TreeNode *root = new TreeNode(i); root->left = left[l]; root->right = right[r]; ret.push_back(root); } } } return ret; } };
tips:
直接学习大神的代码
http://bangbingsyb.blogspot.sg/2014/11/leetcode-unique-binary-search-trees-i-ii.html
一开始一直有一个疑问,如果min==max的时候(即只有一个元素的时候)能构造一个新的节点返回么?
肯定是可以的。因为这时left返回的是含有一个NULL的vector,right返回的是含有一个NULL的vector;两个vector的长度都是1,因此可以构造出这个新的点。
时间: 2024-10-25 05:51:17