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
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
ref:http://www.cnblogs.com/feiling/p/3296156.html
http://fisherlei.blogspot.com/2013/03/leetcode-unique-binary-search-trees-ii.html
划分成左右子树分别进行构造,当左右子树所有可能情况都构造完毕后,加上node即可
这里根节点可能情况为1,2,....,n
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; left = null; right = null; } * } */ public class Solution {public ArrayList<TreeNode> generateTrees(int n) { return generate(1,n); } public ArrayList<TreeNode> generate(int start, int end){ // 存放所有可能的unique BST的root ArrayList<TreeNode> res = new ArrayList<TreeNode>(); if(start > end){ res.add(null); return res; } for(int i = start; i <= end; i++){ // 以 i 为树根的情况,分别递归得到所有的左子树和右子树的所有可能的组合 ArrayList<TreeNode> leftSubTree = generate(start, i-1); ArrayList<TreeNode> rightSubTree = generate(i+1, end); for(int j = 0; j<leftSubTree.size(); j++){ for(int k = 0; k<rightSubTree.size(); k++){ // 创建树根 TreeNode root = new TreeNode(i); // 排列组合所有可能的unique的BST root.left = leftSubTree.get(j); root.right = rightSubTree.get(k); res.add(root); } } } return res; } }