题目:
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?
题目:
这题要求将每个子树输出,思想就是对于n,以1-n为根节点,然后左右子树分别是比其小和比其大的节点构成的,对左右子树的的形态也要使用遍历,代码中使用的是foreach遍历:for(i:j)这种形式
1 /** 2 * Definition for a binary tree node. 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 vectorgenerateTrees(int n) {13 if (n == 0) return generate(1, 0);14 return generate(1, n);15 }16 private:17 vector generate(int start, int end) {18 vector subTree;19 if (start > end) {20 subTree.push_back(nullptr);21 return subTree;22 }23 for (int k = start; k <= end; k++) {24 vector leftSubs = generate(start, k - 1);25 vector rightSubs = generate(k + 1, end);26 for (auto i : leftSubs) {27 for (auto j : rightSubs) {28 TreeNode *node = new TreeNode(k);29 node->left = i;30 node->right = j;31 subTree.push_back(node);32 }33 }34 }35 return subTree;36 }37 };