题目:
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.
链接: http://leetcode.com/problems/unique-binary-search-trees-ii/
6/5/2017
抄的
4ms, 52%
思路:以1-n里每一个值为root,找到所有的情况
注意的问题
1. 递归退出时需要add null,这个也作为叶子节点
2. 左子树和右子树也是通过两个范围内所有的值作为left, right来建的
3. 不理解时间复杂度和空间复杂度:exponential complexity
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<TreeNode> generateTrees(int n) { 12 if (n <= 0) { 13 return new ArrayList<>(); 14 } 15 return generateTrees(1, n); 16 } 17 18 private List<TreeNode> generateTrees(int lo, int hi) { 19 List<TreeNode> ret = new ArrayList<>(); 20 if (lo > hi) { 21 ret.add(null); 22 return ret; 23 } 24 for (int i = lo; i <= hi; i++) { 25 List<TreeNode> left = generateTrees(lo, i - 1); 26 List<TreeNode> right = generateTrees(i + 1, hi); 27 28 for (TreeNode l: left) { 29 for (TreeNode r: right) { 30 TreeNode root = new TreeNode(i); 31 root.left = l; 32 root.right = r; 33 ret.add(root); 34 } 35 } 36 } 37 return ret; 38 } 39 }
别人的DP做法
https://discuss.leetcode.com/topic/2940/java-solution-with-dp
更多讨论
https://discuss.leetcode.com/category/103/unique-binary-search-trees-ii