Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- ListNode* ghead;
- int getSize(ListNode *head){
- int sz = 0;
- while(head){
- sz++;
- head = head->next;
- }
- return sz;
- }
- TreeNode* convertListToBST(int l, int r){
- if(l > r) return NULL;
- int mid = (l+r)>>1;
- // Left node.
- TreeNode *left = convertListToBST(l, mid-1);
- // Middle node.
- TreeNode *node = new TreeNode(ghead->val);
- ghead = ghead->next;
- //Right node.
- TreeNode *right = convertListToBST(mid+1, r);
- //Assign left, right and return node.
- node->left = left;
- node->right = right;
- return node;
- }
- TreeNode* sortedListToBST(ListNode* head) {
- int sz = getSize(head);
- ghead = head;
- return convertListToBST(0, sz-1);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement