zoukankan      html  css  js  c++  java
  • 19.2.24 [LeetCode 95] Unique Binary Search Trees II

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

    Example:

    Input: 3
    Output:
    [
      [1,null,3,2],
      [3,2,null,1],
      [3,1,null,null,2],
      [2,1,3],
      [1,null,2,null,3]
    ]
    Explanation:
    The above output corresponds to the 5 unique BST's shown below:
    
       1         3     3      2      1
               /     /      /       
         3     2     1      1   3      2
        /     /                        
       2     1         2                 3

    题意

    给定一数n,求1-n所组成的所有可能的BST树的集合

    题解

     1 class Solution {
     2 public:
     3     vector<TreeNode*> build(int s, int e) {
     4         if (s > e)return vector<TreeNode*>();
     5         vector<TreeNode*>ans;
     6         if (s == e) {
     7             TreeNode*tmp = new TreeNode(s);
     8             ans.push_back(tmp);
     9             return ans;
    10         }
    11         for (int i = s; i <= e; i++) {
    12             vector<TreeNode*>left = build(s, i - 1), right = build(i + 1, e);
    13             for(int j=0;j<left.size();j++)
    14                 for (int k = 0; k < right.size(); k++) {
    15                     TreeNode*tmp = new TreeNode(i);
    16                     tmp->left = left[j], tmp->right = right[k];
    17                     ans.push_back(tmp);
    18                 }
    19             if (left.size() == 0 || right.size() == 0) {
    20                 for (int j = 0; j < left.size(); j++) {
    21                     TreeNode*tmp = new TreeNode(i);
    22                     tmp->left = left[j];
    23                     ans.push_back(tmp);
    24                 }
    25                 for (int j = 0; j < right.size(); j++) {
    26                     TreeNode*tmp = new TreeNode(i);
    27                     tmp->right = right[j];
    28                     ans.push_back(tmp);
    29                 }
    30             }
    31         }
    32         return ans;
    33     }
    34     vector<TreeNode*> generateTrees(int n) {
    35         return build(1, n);
    36     }
    37 };
    View Code
  • 相关阅读:
    Ajax 导出Excel 方式
    配置文件类型
    Ionic 发布Release 版本
    $cordovaNetwork 使用
    Web Api 跨域问题
    Python学习(五)--字典
    Python学习(四)--字符串
    Python学习(三)--列表和元组
    mac下安装HTMLTestRunner
    mac下selenium+python环境搭建
  • 原文地址:https://www.cnblogs.com/yalphait/p/10428275.html
Copyright © 2011-2022 走看看