给定一个有序的链表或者数组,构造一棵二叉搜索树

217 篇文章 0 订阅
174 篇文章 2 订阅

思路:找到链表的中节点,就是二叉树的根节点,然后递归构造左右子树

链表:

    TreeNode *sortedListToBST(ListNode *head) {
        return ListToBST(head,NULL);
    }
    TreeNode* ListToBST(ListNode* head,ListNode* tail){
        if(head==tail)
            return NULL;
        ListNode* fast=head;
        ListNode* slow=head;
        
        while(fast!=tail&&fast->next!=tail){
            slow=slow->next;
            fast=fast->next->next;
        }
        TreeNode* root=new TreeNode(slow->val);
        root->left=ListToBST(head,slow);
        root->right=ListToBST(slow->next,tail);
        return root; 
    }

数组:

    TreeNode *sortedArrayToBST(vector<int> &num) {
        int len=num.size();
        if(len==0)
            return NULL;
        TreeNode* root=new TreeNode(num[len/2]);
        vector<int> leftNum(num.begin(),num.begin()+len/2);
        vector<int> rightNum(num.begin()+len/2+1,num.end());
        root->left=sortedArrayToBST(leftNum);
        root->right=sortedArrayToBST(rightNum);
        return root;
    }
思路二:

    TreeNode *sortedArrayToBST(vector<int> &num) {
       return ArrayToList(num,0,num.size());
    }
    TreeNode* ArrayToList(vector<int> num,int start,int end){
        if(start>=end)
            return NULL;
        int mid=(start+end)>>1;
        TreeNode* root=new TreeNode(num[mid]);
        root->left=ArrayToList(num,start,mid);
        root->right=ArrayToList(num,mid+1,end);
        return root;
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值