zoukankan      html  css  js  c++  java
  • Unique Binary Search Trees II

     1 public class Solution {
     2     public ArrayList<TreeNode> generateTrees(int n) {
     3         // IMPORTANT: Please reset any member data you declared, as
     4         // the same Solution instance will be reused for each test case.
     5         return generate(1, n);
     6     }
     7     public ArrayList<TreeNode> generate(int start, int end){
     8         ArrayList<TreeNode> subTree = new ArrayList<TreeNode>();
     9         if(start > end){
    10             subTree.add(null);
    11             return subTree;
    12         }
    13         
    14         for(int i = start; i <= end; i++){
    15             ArrayList<TreeNode> leftSubTree = generate(start, i - 1);
    16             ArrayList<TreeNode> rightSubTree = generate(i + 1, end);
    17             for(int j = 0; j < leftSubTree.size(); j++){
    18                 for(int k = 0; k < rightSubTree.size(); k++){
    19                     TreeNode node = new TreeNode(i);
    20                     node.left = leftSubTree.get(j);
    21                     node.right = rightSubTree.get(k);
    22                     subTree.add(node);
    23                 }
    24             }
    25         }
    26         return subTree;
    27     }
    28 }
  • 相关阅读:
    Java String 乱码
    HBase非原理性浅析
    git cherry-pick
    数据结构之队列
    数据结构之栈
    算法之简单排序
    数据结构之数组
    数据结构简介
    Java类型信息
    基数排序
  • 原文地址:https://www.cnblogs.com/jasonC/p/3419237.html
Copyright © 2011-2022 走看看