Use DP to generate unique distinct binary trees;
Create to both integer value, one "start" to represent the lowest value, and the other "end" to represent the highest valu E The range of the whole true is from start to end, initially start = 1, end = N.
Suppose I was the current root and then the left subtree value should was start-i-1, the right subtree value should be i+1- End Thus, we ' re going to check the different situation of the range value.
Case 1:if (Start > End), this means invalid value range of left subtree, thus the left subtree should is NULL, add null to the list.
Case 2:if (start = = end), this exactly points to one node, add the node to the list.
Case 3:the left situation are end > start, we can use a loop to set every node's value from start to end, as the root node, and recursively call this method to get the left subtree list and the right subtree list, then traverse each list to Get all the possible combination of left subtree and right subtree, set the Root.left to being the root of the left sub tree And Root.right to is the root of the right sub tree. After this, we get a unique tree, and add the root to the list.
Code:
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicList<treenode> Generatetrees (intN) {List<TreeNode> ret =NewArraylist<>(); if(n = = 0)returnret; returnListtrees (1, N); } PublicList<treenode> Listtrees (intStartintend) { if(Start >end) {List<TreeNode> list =NewArraylist<>(); List.add (NULL); returnlist; } if(Start = =end) {List<TreeNode> list =NewArraylist<>(); List.add (NewTreeNode (start)); returnlist; } List<TreeNode> list =NewArraylist<>(); for(inti = start; I <= end; i++) {List<TreeNode> lefttrees = listtrees (Start, i-1); List<TreeNode> righttrees = listtrees (i+1, end); for(intj = 0; J < Lefttrees.size (); J + +){ for(intk = 0; K < Righttrees.size (); k++) {TreeNode root=NewTreeNode (i); List.add (root); Root.left=Lefttrees.get (j); Root.right=Righttrees.get (k); } } } returnlist; } }
Jan 26-unique Binary Search Trees; DP; Trees; Recursion & iteration;