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.
Problem Solving Ideas:
Refer to Java for leetcode 096 Unique Binary Search trees ideas, the subject is easy to solve. Note that if you try to use an object's reference without copying it, you can't get the correct result, but you can also use DFS, but given the Java object-oriented features, we're using Java for Leetcode 096 Unique Binary Search Trees the idea of it.
The Java implementation is as follows:
static public list<treenode> generatetrees (int n) {list<treenode> List = new arraylist<treenode> (); (n = = 0) {list.add (null); return list;} if (n = = 1) {List.add (new TreeNode (1)); return list;} for (int k = 0, K <= n-1; k++) {list<treenode> left = Generatetrees (k); List<treenode> right = Generatetrees (N-k-1), for (TreeNode rightnode:right) plus (Rightnode, k + 1); for (TreeNode Leftnode:left) {for (TreeNode rightnode:right) {TreeNode TN = new TreeNode (k + 1); Tn.left = Treenodeclone (Leftnode); Tn.right = Treenodeclone (Rightnode); List.add (TN);}}} return list;} public static void plus (TreeNode root, int num) {if (root = null) Return;root.val + = Num;plus (root.left, num);p LUs (Root.ri Ght, num);} public static TreeNode Treenodeclone (TreeNode TN1) {if (tn1==null) return null; TreeNode tn2=new TreeNode (tn1.val); Tn2.left=treenodeclone (Tn1.left); Tn2.right=treenodeclone (tn1.right); return TN2;}
Java for Leetcode 095 Unique Binary Search Trees II