lintcode-排序列表转换为二分查找树-106

来源:互联网 发布:tiger水杯 知乎 编辑:程序博客网 时间:2024/06/06 13:11
/** * Definition of ListNode * class ListNode { * public: *     int val; *     ListNode *next; *     ListNode(int val) { *         this->val = val; *         this->next = NULL; *     } * } * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {    void Free(ListNode *head){        ListNode *p=head;        while(p){            head=p->next;            free(p);            p=head;        }    }    vector<int> ListToArr(ListNode *head){  //想法就是把链表的数据存储到数组中        vector<int> base;                while(head){            base.push_back(head->val);            head=head->next;        }        Free(head);        return base;    }        TreeNode* helper(const vector<int> &arr,int left,int right){         if(left>right)            return nullptr;        int mid=(left+right)/2;        TreeNode *root=new TreeNode(arr[mid]);                root->left=helper(arr ,left,mid-1);        root->right=helper(arr,mid+1,right);                return root;    }public:        TreeNode *sortedListToBST(ListNode *head) {        if(head==nullptr)            return nullptr;        vector<int> ret=ListToArr(head);            return helper(ret,0,ret.size()-1);     }};

0 0
原创粉丝点击