• 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 };
  • 相关阅读:
    数据的输入输出
    运算符和表达式
    深入理解Magento – 第三章 – 布局,块和模板
    压抑中......
    css控制图片自适应大小
    问来北京的追求是什么
    magento目录结构精编版
    无所事事的日子。
    jQuery实现等比例缩放大图片让大图片自适应页面布局
    MVC 小常识
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/6005577.html
Copyright © 2020-2023  润新知