码迷,mamicode.com
首页 > 其他好文 > 详细

Unique Binary Search Trees II

时间:2016-01-08 07:05:20      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Given n, generate all structurally unique BST‘s (binary search trees) that store values 1...n.

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


/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @paramn n: An integer
     * @return: A list of root
     */
    public List<TreeNode> generateTrees(int n) {
        // write your code here
        return generate(1,n);
        
    }
    
    public List<TreeNode> generate(int left,int right)
    {
        List<TreeNode> res= new ArrayList<TreeNode>();
        if(left>right)
        {
            res.add(null);
            return res;
        }
        
        for(int i=left;i<=right;i++)
        {
            List<TreeNode> lefts= generate(left,i-1);
            List<TreeNode> rights= generate(i+1,right);
            
            for(int j=0;j<lefts.size();j++)
            {
                for(int k=0;k<rights.size();k++)
                {
                    TreeNode root =new TreeNode(i);
                    root.left=lefts.get(j);
                    root.right=rights.get(k);
                    
                    res.add(root);
                }
                
            }
        }
        
        return res;
    }
}

 

Unique Binary Search Trees II

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5111862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!