标题: | |
通过率: | 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?
在第一个版本中要求的是说出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 ListgenerateTrees(int n) {12 return getTree(1,n);13 }14 public ArrayList getTree(int left,int right){15 ArrayList result=new ArrayList ();16 if(left>right){17 result.add(null);18 return result;19 }20 for(int i=left;i<=right;i++){21 ArrayList leftt=getTree(left,i-1);22 ArrayList rightt=getTree(i+1,right);23 for(int j=0;j