leetcode+构建二叉搜索树,典型递归应用

点击打开链接
//典型自上而下 递归使用
//只要构造出一种情况,因此不需要回溯
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <string.h>
#include <algorithm>
#include <vector>
#include <numeric>
#include <limits>
#include <math.h>
#include <queue>
using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
    TreeNode *sortedArrayToBST(vector<int>& num, int l, int r)
    {
        if(l>r) return NULL;
        int m=(l+r)/2;
        TreeNode *root=new TreeNode(num[m]);//中间节点赋值了
        root->left = sortedArrayToBST(num, l, m-1);
        root->right = sortedArrayToBST(num, m+1, r);
        return root;
    }
    TreeNode* sortedListToBST(ListNode* head) {
        vector<int> vi;
        for(ListNode* p=head; p!=NULL;p=p->next){
            vi.push_back(p->val);
        }
        return sortedArrayToBST(vi, 0, vi.size()-1);//起始点。终止点
    }
};
int main()
{
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值