88 * Date 11/07/2015
99 * @author Tushar Roy
1010 *
11- * Given an inorder traversal construct all binary search trees possible .
11+ * Given n, generate all structurally unique BST's ( binary search trees) that store values 1...n .
1212 * Total number of binary search tree possible is Catalan number.
13+ *
14+ * https://leetcode.com/problems/unique-binary-search-trees-ii/
1315 */
1416public class ConstructAllBinaryTreeFromInorderTraversal {
1517
16- public List <Node > construct (int inorder []) {
17- return construct (inorder , 0 , inorder .length - 1 );
18+ public List <Node > generateTrees (int n ) {
19+ if (n == 0 ) {
20+ return Collections .emptyList ();
21+ }
22+ return construct (1 , n );
1823 }
1924
20- private List <Node > construct (int inorder [], int start , int end ) {
25+ private List <Node > construct (int start , int end ) {
2126 if (start > end ) {
2227 return Collections .singletonList (null );
2328 }
2429 List <Node > allTrees = new ArrayList <>();
2530 for (int root = start ; root <= end ; root ++) {
2631 //get all subtrees from left and right side.
27- List <Node > allLeftSubstrees = construct (inorder , start , root - 1 );
28- List <Node > allRightSubstrees = construct (inorder , root + 1 , end );
32+ List <Node > allLeftSubstrees = construct (start , root - 1 );
33+ List <Node > allRightSubstrees = construct (root + 1 , end );
2934 //iterate through them in all combination and them connect them to root
3035 //and add to allTrees.
3136 for (Node left : allLeftSubstrees ) {
3237 for (Node right : allRightSubstrees ) {
33- Node node = Node .newNode (inorder [ root ] );
38+ Node node = Node .newNode (root );
3439 node .left = left ;
3540 node .right = right ;
3641 allTrees .add (node );
@@ -52,9 +57,8 @@ public void printAllTrees(List<Node> allTrees) {
5257 }
5358
5459 public static void main (String args []) {
55- int inorder [] = {1 , 2 , 3 , 4 , 5 };
5660 ConstructAllBinaryTreeFromInorderTraversal ct = new ConstructAllBinaryTreeFromInorderTraversal ();
57- List <Node > allTrees = ct .construct ( inorder );
61+ List <Node > allTrees = ct .generateTrees ( 3 );
5862 ct .printAllTrees (allTrees );
5963 }
6064}
0 commit comments