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 *> generateTrees(int n) { return generateTrees(1,n); } vector<TreeNode *>generateTrees(int s,int e){ vector<TreeNode *> res; if(s>e) res.push_back(0);//the default element is 0 else if(s==e) res.push_back(new TreeNode(s));//new else if(s<e){ for(int i=s;i<=e;i++){ vector<TreeNode *>left=generateTrees(s,i-1);//the left subtrees vector<TreeNode *>right=generateTrees(i+1,e);//the right subtrees for(int j=0;j<left.size();j++){ for(int k=0;k<right.size();k++){ TreeNode *proot=new TreeNode(i);//every tree has a rootNode proot->left=left[j]; proot->right=right[k]; res.push_back(proot); } } } } return res; } };
时间: 2024-10-22 02:29:09