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

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

    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 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 private:
    12     vector<TreeNode*> helper(int start, int end) {
    13         if (start > end) {
    14             return vector<TreeNode*>{nullptr};
    15         }
    16         if (start == end) {
    17             TreeNode* root = new TreeNode(start);
    18             return vector<TreeNode*>{root};
    19         }
    20         vector<TreeNode*> result;
    21         for (int i = start; i <= end; ++i) {
    22             vector<TreeNode*> leftV = helper(start, i - 1);
    23             vector<TreeNode*> rightV = helper(i + 1, end);
    24             for (int j = 0; j < leftV.size(); ++j) {
    25                 for (int k = 0; k < rightV.size(); ++k) {
    26                     TreeNode* root = new TreeNode(i);
    27                     root -> left = leftV[j];
    28                     root -> right = rightV[k];
    29                     result.push_back(root);
    30                 }
    31             }
    32         }
    33         return result;
    34     }
    35 public:
    36     vector<TreeNode*> generateTrees(int n) {
    37         vector<TreeNode*> result;
    38         if (n == 0) {
    39             return result;
    40         }
    41         result = helper(1, n);
    42         return result;
    43     }
    44 };
  • 相关阅读:
    typescript提示implicitly has an 'any' type 问题
    element-ui中的table可分页多选功能-记住上一页勾选数据
    CSS加载会阻塞页面显示?
    网络流(EK算法)
    网络流(dinic算法)
    洛谷p1120小木棍(剪枝优化)
    三种背包模板
    HDU2089-不要62(数位dp)
    windy数(数位dp)
    素数判定(待填坑)
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/6005577.html
Copyright © 2011-2022 走看看