leetcode------Unique Binary Search Trees II
标题: | Unique Binary Search Trees II |
通过率: | 27.5% |
难度: | 中等 |
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.
在第一个版本中要求的是说出BST数量,本题要求把BST全部都输出,用list去储存一个每个可解方案的root,跟第一版本的类型相似,尝试每一个元素作为root那么就把一组数分成了左右,然后去处理左边和右边,这样就把全部类型都列举出来了,还是递归的思想;
具体看代码:
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 return getTree(1,n); 13 } 14 public ArrayList<TreeNode> getTree(int left,int right){ 15 ArrayList<TreeNode> result=new ArrayList<TreeNode>(); 16 if(left>right){ 17 result.add(null); 18 return result; 19 } 20 for(int i=left;i<=right;i++){ 21 ArrayList<TreeNode> leftt=getTree(left,i-1); 22 ArrayList<TreeNode> rightt=getTree(i+1,right); 23 for(int j=0;j<leftt.size();j++){ 24 for(int k=0;k<rightt.size();k++){ 25 TreeNode root=new TreeNode(i); 26 root.left=leftt.get(j); 27 root.right=rightt.get(k); 28 result.add(root); 29 } 30 } 31 } 32 return result; 33 } 34 }