标签:
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
Key to the solution is to divide the problem into two sub-problems. Unlike "Unique Binary Search Trees", this problem is NP-hard.
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 return generateTreesHelper(1, n); 13 } 14 private List<TreeNode> generateTreesHelper(int start, int end) { 15 List<TreeNode> result = new ArrayList<TreeNode>(); 16 if (start > end) { 17 result.add(null); 18 return result; 19 } 20 for (int i = start; i <= end; i++) { 21 List<TreeNode> lefts = generateTreesHelper(start, i - 1); 22 List<TreeNode> rights = generateTreesHelper(i + 1, end); 23 for (TreeNode left : lefts) { 24 for (TreeNode right : rights) { 25 TreeNode tmp = new TreeNode(i); 26 tmp.left = left; 27 tmp.right = right; 28 result.add(tmp); 29 } 30 } 31 } 32 return result; 33 } 34 }
Unique Binary Search Trees II 解答
标签:
原文地址:http://www.cnblogs.com/ireneyanglan/p/4825083.html