Unique Binary Search Tree 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
分析:这道题与unique binary search tree I不同在于我们要生成所以的二叉查找树并返回树的根。同样我们用递归的方法,如果是空树我们加入一个NULL指针,这个对于简化代码是有帮助的。
如果在空树的情况是我们不加入NULL,而是让<TreeNode *> res为空,那么在通过左右两个子树组成新树时,代码会繁琐很多。因为我们必须要处理左子树、右子树是否为空总共四种情况。
1 class Solution { 2 public: 3 vector<TreeNode *> generateTrees(int n) { 4 return generate_Trees(1,n); 5 } 6 7 vector<TreeNode *> generate_Trees(int l, int r){ 8 vector<TreeNode *> result; 9 10 if(l > r) 11 result.push_back(NULL); 12 13 for(int i = l; i <= r; i++){ 14 vector<TreeNode *> left = generate_Trees(l, i-1); 15 vector<TreeNode *> right = generate_Trees(i+1, r); 16 for(auto j:left) 17 for(auto k:right){ 18 TreeNode *root = new TreeNode(i); 19 root->left = j; 20 root->right = k; 21 result.push_back(root); 22 } 23 } 24 25 return result; 26 } 27 };