Leetcode 95.二叉树搜索不同二叉搜索数

Leetcode 95.二叉树搜索不同二叉搜索数

题目
给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。

示例:

输入: 3
输出:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:

思路:
对于连续整数序列[begin,end]中一点i,以i作为节点的BST,
左边的节点可以有vector<TreeNode*> left=help(begin,i-1);
右边的节点为 vector<TreeNode*> right=help(i+1,end);
生生的以当前i为根结点的BST(子)树有left_nodes.size() * right_nodes.size()个,遍历每种情况,即可生成以i为根节点的BST序列;
然后以for循环使得[left, right]中每个结点都能生成子树序列。

代码片.

 * 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) {
        if(n==0)
            return vector<TreeNode*>{};
        return help(1,n);
    }
    
     vector<TreeNode*> help(int begin,int end){
         vector<TreeNode*> v;
         
         if(begin>end)
         {
             v.push_back(NULL);
             return v;
         }
             for(int i=begin;i<=end;++i)
             {
                vector<TreeNode*> left=help(begin,i-1);//i左边的序列作为左子树节点
                 vector<TreeNode*> right=help(i+1,end);//i右边的序列作为右字数的节点
                 for(auto l:left)
                 {
                     for(auto r:right){
                    TreeNode* root = new TreeNode(i);
                    root->left = l;
                    root->right = r;
                    v.push_back(root);     
                 }
             }
             }
             return v; 
         }

             
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值