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

LeetCode 95. Unique Binary Search Trees II

时间:2017-04-15 11:45:19      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:binary   判断   bsp   example   void   res   stat   strong   rally   

题目如下:

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) if(n<=0) 要判断,否则,n=0的测试结果是 [[]] ,而正确应该返回 []  

(2) if (s > e) {res.add(null);} 这里不能直接{return null;}

 

本题代码:

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yuanxu on 17/4/13.
 */
public class DP95 {

    public static List<TreeNode> generateTrees(int n) {
        if (n <= 0) return new ArrayList<>();
        return generateSubtrees(1, n);
    }

    private static List<TreeNode> generateSubtrees(int s, int e) {
        List<TreeNode> res = new ArrayList<TreeNode>();
        if (s > e) { res.add(null); }

        for (int i=s; i<=e; ++i) {
            List<TreeNode> leftTrees = generateSubtrees(s, i-1);
            List<TreeNode> rightTrees = generateSubtrees(i+1, e);

            for (TreeNode left : leftTrees) {
                for (TreeNode right : rightTrees) {
                    TreeNode root = new TreeNode(i);
                    root.left = left;
                    root.right = right;
                    res.add(root);
                }
            }
        }
        return res;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    /**
     * @test
     */
    public static void main(String args[]) {
        int n = 0;
        System.out.println(generateTrees(n).get(0).val);
    }

}

 

ref : https://discuss.leetcode.com/topic/3079/a-simple-recursive-solution

LeetCode 95. Unique Binary Search Trees II

标签:binary   判断   bsp   example   void   res   stat   strong   rally   

原文地址:http://www.cnblogs.com/pinganzi/p/6713620.html

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