/** * 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: vector<int> temp; TreeNode* build(int l,int r) { if(l==r) return NULL; int mid=l+r>>1; TreeNode* root=new TreeNode(temp[mid]); root->left=build(l,mid); root->right=build(mid+1,r); return root; } TreeNode* sortedListToBST(ListNode* head) { ListNode *h=head; while(h) { temp.push_back(h->val); h=h->next; } return build(0,temp.size()); } };