Unique Binary Search Trees II
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.
Hide Tags Tree Dynamic Programming
SOLUTION 1:
使用递归来做。
1. 先定义递归的参数为左边界、右边界,即1到n.
2. 考虑从left, 到right 这n个数字中选取一个作为根,余下的使用递归来构造左右子树。
3. 当无解时,应该返回一个null树,这样构造树的时候,我们会比较方便,不会出现左边解为空,或是右边解为空的情况。
4. 如果说左子树有n种组合,右子树有m种组合,那最终的组合数就是n*m. 把这所有的组合组装起来即可
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; left = null; right = null; } 8 * } 9 */ 10 public class Solution { 11 public List<TreeNode> generateTrees(int n) { 12 // 0.07 13 return dfs(1, n); 14 } 15 16 public List<TreeNode> dfs(int left, int right) { 17 List<TreeNode> ret = new ArrayList<TreeNode>(); 18 19 // The base case; 20 if (left > right) { 21 ret.add(null); 22 return ret; 23 } 24 25 for (int i = left; i <= right; i++) { 26 List<TreeNode> lTree = dfs(left, i - 1); 27 List<TreeNode> rTree = dfs(i + 1, right); 28 for (TreeNode nodeL: lTree) { 29 for (TreeNode nodeR: rTree) { 30 TreeNode root = new TreeNode(i); 31 root.left = nodeL; 32 root.right = nodeR; 33 ret.add(root); 34 } 35 } 36 } 37 38 return ret; 39 } 40 }
CODE:
来源:https://www.cnblogs.com/yuzhangcmu/p/4256291.html