Given an integer n
, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
Constraints:
0 <= n <= 8
class Solution { public List<TreeNode> generateTrees(int n) { if(n == 0) return new ArrayList(); return build(1, n); } public List<TreeNode> build(int start, int end) { List<TreeNode> list = new ArrayList(); if(start > end) list.add(null); for(int indx = start; indx <= end; indx++) { List<TreeNode> leftchild = build(start, indx - 1); List<TreeNode> rightchild = build(indx + 1, end); for(TreeNode left: leftchild) { for(TreeNode right : rightchild) { TreeNode root = new TreeNode(indx); root.left = left; root.right = right; list.add(root); } } } return list; } }
we have nodes from 1 to n, and everyone can be the root, so we from 1 to n pick one as the root and try to find its left childs and right childs. How?
we find its lefttree by build(start, index - 1), right tree by build(index + 1, end), then we know we have leftchild.size() * right.size() combinations, so we make a double for-loop and build every combination and add to the result.