欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
95 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
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode *> generateUtil(int start, int end) { vector<TreeNode *> ans; if(start > end) { ans.push_back(NULL); return ans; } for(int i = start; i <= end; ++i) { vector<TreeNode*> leftTrees = generateUtil(start, i-1); vector<TreeNode*> rightTrees = generateUtil(i+1, end); for(int l = 0; l < leftTrees.size(); ++l) { for(int r = 0; r < rightTrees.size(); ++r) { TreeNode* root = new TreeNode(i); root->left = leftTrees[l]; root->right = rightTrees[r]; ans.push_back(root); } } } return ans; } vector<TreeNode *> generateTrees(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function return generateUtil(1, n); } };
时间: 2024-10-27 08:28:28