[leetcode] Convert Sorted List to Binary Search Tree

来源:互联网 发布:数据分析软件有哪些 编辑:程序博客网 时间:2024/05/29 02:13

Convert Sorted List to Binary Search Tree

解法:

把链表转换为vector之后,解法和上题一样。

class Solution {public:        TreeNode *sortedListToBSTbyIndex(vector<int> &num,int begin,int end){        if (begin>end) {            return nullptr;        }        int mid=begin+(end-begin)/2;        TreeNode *pleft=sortedListToBSTbyIndex(num, begin, mid-1);        TreeNode *pright=sortedListToBSTbyIndex(num, mid+1, end);                TreeNode *node=new TreeNode(num[mid]);        node->left=pleft;        node->right=pright;        return node;    }        TreeNode *sortedListToBST(ListNode *head) {        if (head==nullptr) {            return nullptr;        }        vector<int> vt;        while (head!=nullptr) {            vt.push_back(head->val);            head=head->next;        }                return sortedListToBSTbyIndex(vt,0,vt.size()-1);    }};


0 0