leetcode No109. Convert Sorted List to Binary Search Tree

来源:互联网 发布:浩鹏图纸加密软件 编辑:程序博客网 时间:2024/06/14 05:38

Question:

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

把有序链表转化成平衡的BST

Algorithm:

把链表转化成数组,再根据leetcode No108. Convert Sorted Array to Binary Search Tree的方法
找到数组中间的元素,作为根节点,则根节点左边是左子树,根节点右边是右子树,接着递归

Accepted Code:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; *//** * 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:    TreeNode* sortedListToBST(ListNode* head) {        if(head==NULL)            return NULL;        vector<int> v;        ListNode* p=head;        while(p)        {            v.push_back(p->val);            p=p->next;        }        return BuildTree(v,0,v.size()-1);    }    TreeNode* BuildTree(vector<int>& nums,int first,int end)    {        if(first>end)return NULL;        if(first==end)return new TreeNode(nums[first]);        int mid=(first+end)/2;        TreeNode* root=new TreeNode(nums[mid]);        root->left=BuildTree(nums,first,mid-1);        root->right=BuildTree(nums,mid+1,end);        return root;    }};


0 0