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

    95. Unique Binary Search Trees II

    相关链接

    leetcode

    描述

      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
    

    思路1递归解决

    按照根节点来分类的话,可以分成n类;
    假设要生成根节点为i的所有BST,可以先生成(0 到 i-1)的所有左子树和(i+1到n)的所有右子树,然后两两组合;

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<TreeNode*> generateTrees(int n) {
            vector<TreeNode*> tree;
            if (n == 0)
                return tree;
            dfs(1, n, tree);
            return tree;
        }
    
        void dfs(int start, int end, vector<TreeNode*> &tree)
        {
            if (start > end)
            {
                tree.push_back(NULL);
            }
    
         for(int i = start; i <= end; i++){
             vector<TreeNode*> left;
             vector<TreeNode*> right;
    
             dfs(start, i-1, left);
             dfs(i+1, end, right);
    
             for(int k = 0; k < left.size(); k++)
                 for(int j = 0; j < right.size(); j++)
                 {
                     TreeNode * root = new TreeNode(i);
                     root->left = left[k];
                     root->right = right[j];
    
                     tree.push_back(root); 
                 }
        }
    };
    

    参考
    csdn

    blogs record our growth
  • 相关阅读:
    使用cocoapods出现问题fetch of the ‘master’ 的解决方法
    说说ASP.NET的表单验证
    php分页类
    php校验
    mySQL时间
    asp .NET弹出窗口 汇总(精华,麒麟创想)
    (转)MVC 3 数据验证 Model Validation 详解
    (转)linux性能优化总结
    (转)ASP.NET缓存全解析6:数据库缓存依赖
    SQL Server是如何让定时作业
  • 原文地址:https://www.cnblogs.com/qwfand/p/12553466.html
Copyright © 2011-2022 走看看