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
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}"
.思路:列出所有的二叉搜索树,只能是枚举了,而且是递归枚举;故使用DFS来枚举出所有的可能。
/** * 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 *> generateBST(int left,int right) { vector<TreeNode *> result; if(left>right) { result.push_back(NULL); return result; } for(int i=left;i<=right;i++) { vector<TreeNode *> leftTree=generateBST(left,i-1); vector<TreeNode *> rightTree=generateBST(i+1,right); for(int j=0;j<leftTree.size();j++) { for(int k=0;k<rightTree.size();k++) { TreeNode *root=new TreeNode(i); result.push_back(root); root->left=leftTree[j]; root->right=rightTree[k]; } } } return result; } vector<TreeNode *> generateTrees(int n) { vector<TreeNode *> result; result=generateBST(1,n); return result; } };