Unique Binary Search Trees: To generate the number of two-fork sort trees.
Given N, how many structurally unique BST's (binary search trees) that store values 1 ... n?
For example,
Given N = 3, there is a total of 5 unique BST ' s.
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
Algorithm analysis: Similar to the ladder, simple dynamic planning problems. When the root node is I, the node that is smaller than I is i-1, and the node of I is n-i, so I can generate a two-fork sort tree for the root node.
Nums[n] + = Nums[i-1]*nums[n-i],i from 1 to N.
public class Uniquebinarysearchtrees{public int numtrees (int n) { if (n <= 0) { return 0; } int[] res = new Int[n+1]; Res[0] = 1; RES[1] = 1; for (int i = 2; I <= n; i + +) { for (int j = 1; J <= I; j + +)//j as root node { Res[i] + = res[j-1]*res[i-j];< c12/>} } return res[n];}}
Unique Binary Search Trees2: A collection of root nodes that generate a two-fork sort tree
Given an integer 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
Algorithm analysis: This is not the number, but to generate root nodes. Use recursion.
public class Uniquebinarysearchtreesii {public list<treenode> generatetrees (int n) {if (n <= 0) {return new Arrayl Ist<treenode> ();} return helper (1, n); } Public list<treenode> Helper (int m, int n) {list<treenode> res = new arraylist<> (); if (M > N) {res.add ( NULL); return res;} for (int i = m; i <= N; i + +) {//i is the root node list<treenode> ls = helper (m, i-1);//i node's left subtree list<treenode> rs = helper ( I+1, n); Right subtree of//i node for (TreeNode l:ls) {TreeNode r:rs = new TreeNode (i); curr = TreeNode = Curr.left S.add (Curr);}}} return res;}}
Unique binary search trees,unique binary search Trees2 generate two-fork sort tree