zoukankan      html  css  js  c++  java
  • [leedcode 96] Unique Binary Search Trees II

    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.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        public List<TreeNode> generateTrees(int n) {
            //拿到n个数字后,从中依次选取一个数作为根结点,分别从根节点分成的左右两个分支中选择一个节点作为左右子树的根节点
            return generate(1,n);
        }
        public List<TreeNode> generate(int start,int end){
            List<TreeNode> seq=new ArrayList<TreeNode>();
            if(start>end){
                 seq.add(null);
            }
            else{
                for(int i=start;i<=end;i++){
                List<TreeNode> left=generate(start,i-1);
                List<TreeNode> right=generate(i+1,end);
                
                for(int li=0;li<left.size();li++){
                    for(int ri=0;ri<right.size();ri++){
                        TreeNode root=new TreeNode(i);
                        root.left=left.get(li);
                        root.right=right.get(ri);
                        seq.add(root);
                    }
                }
                }
            }
            return seq;
        }
    }
  • 相关阅读:
    详解扩展欧几里得算法(扩展GCD)
    NOIP 2012 同余方程
    NOIP 2011 观光公交
    NKOJ4330 逛公园
    NKOJ 7.7练习题A IP地址
    NKOJ3777 卡牌操作
    NKOJ3772 看电影
    NKOJ3765 k个最小和
    NKOJ3775 数列操作
    NKOJ3768 数列操作
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4652479.html
Copyright © 2011-2022 走看看