Title:
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
Test Instructions:
Given n, generate all existing and unique two-fork search trees to store the value of 1 ... N .
Like what
Given n = 3, you need to return all 5 two-fork search trees as follows:
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
Algorithm Analysis:
* Similar to "Unique Binary Search Trees"
* The difference is that this problem is more difficult than 1 is not to return the number, but to return all results.
* The basis for solving this problem is still:
* When the array is 1,2,3,4, ... I,.. N, the BST build is unique based on the following principles:
* with I as the root node of the tree, the left sub-tree is composed of [1, i-1], the right subtree is composed of [I+1, N].
* Recursive function is called in the loop to solve the sub-problem
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >/** * Definition for a binary tree node. * public class TreeNode { * int val; * &nbs P TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} *} */public class solution { public arraylist<treenode> generatetrees (int n) { return generatetrees (1, n);//starting with 1 as root, ending with N as root } Private arraylist<treenode> generatetrees (int left, int. right) { &NBS P arraylist<treenode> res = new arraylist<treenode> (); if (left > right) &nb Sp { res.add (null); re Turn res; } for (int i = left; I <= RIGht i++) { arraylist<treenode> lefts = generatetrees (left, i-1);//with I as root node, Zuozi by [1,i-1] composition arraylist<treenode> rights = Generatetrees (i+1, right);//R Sub-tree consists of [I+1, N] for (int j = 0; J < Lefts.size (); j + +) { for (int k = 0; K &L T Rights.size (); k++) { &NBSP ; TreeNode root = new TreeNode (i); Root.left = l Efts.get (j); Root.right = Rights.get (k); Res.add (root)//store all possible lines &NBsp } } } return res; &NB Sp }}</span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Unique Binary Search Trees II