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
题解:递归的枚举1~n的每个节点为根节点,然后递归的利用它左边的节点构造左子树,放在一个list里面;再利用它右边的节点构造右子树,也放在一个list里面;最终枚举两个list里面的左子树和右子树,构建一棵树。
代码如下:
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 private ArrayList<TreeNode> generate(int start,int end){ 12 ArrayList<TreeNode> answer = new ArrayList<TreeNode>(); 13 if(start > end){ 14 answer.add(null); 15 return answer; 16 } 17 18 //for every node from start to right,make it as tree root and recursively build its left and right child tree 19 for(int i = start; i <= end;i++){ 20 ArrayList<TreeNode> left = generate(start, i-1); 21 ArrayList<TreeNode> right = generate(i+1, end); 22 for(TreeNode l:left){ 23 for(TreeNode r:right){ 24 TreeNode root = new TreeNode(i); 25 root.left = l; 26 root.right = r; 27 answer.add(root); 28 } 29 } 30 31 } 32 33 return answer; 34 35 } 36 public List<TreeNode> generateTrees(int n) { 37 return generate(1,n); 38 } 39 }
【leetcode刷题笔记】Unique Binary Search Trees II,布布扣,bubuko.com
【leetcode刷题笔记】Unique Binary Search Trees II
原文:http://www.cnblogs.com/sunshineatnoon/p/3860086.html