95. Unique Binary Search Trees II

Given an integer 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. 每一次都在一个范围内随机选取一个结点作为根。 
2. 每选取一个结点作为根,就把树切分成左右两个子树,直至该结点左右子树为空。

 1     public List<TreeNode> generateTrees(int n) {
 2         if(n < 1)return new ArrayList<TreeNode>();
 3         return createTree(1, n);
 4     }
 5     
 6     public List<TreeNode> createTree(int start, int end) {
 7         List<TreeNode> res = new ArrayList();
 8         if(start > end) {
 9             res.add(null);
10             return res;
11         }
12         for(int i = start; i <= end; i ++) {
13             List<TreeNode> leftChild = createTree(start, i - 1);
14             List<TreeNode> rightChild = createTree(i + 1, end);
15             for(TreeNode left : leftChild) {
16                 for(TreeNode right : rightChild) {
17                     TreeNode root = new TreeNode(i);
18                     root.left = left;
19                     root.right = right;
20                     res.add(root);
21                 }
22             }
23         }
24         return res;
25     }

 

posted @ 2017-10-19 10:44  daniel456  阅读(93)  评论(0编辑  收藏  举报