LeetCode:Convert Sorted List to Binary Search Tree
Convert Sorted List to Binary Search Tree
Total Accepted: 67959
Total Submissions: 224265
Difficulty: Medium
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
Hide Tags
Depth-first Search Linked List
Hide Similar Problems
(M) Convert Sorted Array to Binary Search Tree
code:
Total Accepted: 67959
Total Submissions: 224265
Difficulty: Medium
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
Hide Tags
Depth-first Search Linked List
Hide Similar Problems
(M) Convert Sorted Array to Binary Search Tree
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) {
return sortedListToBST(head, NULL);
}
TreeNode* sortedListToBST(ListNode* head, ListNode *tail) {
if(head == tail) return NULL;
ListNode *fast = head,*slow = head;
while(fast!=tail && fast->next != tail){ //
fast = fast->next->next;
slow = slow->next;
}
TreeNode *root = new TreeNode(slow->val);
root->left = sortedListToBST(head, slow);
root->right = sortedListToBST(slow->next, tail);
return root;
}
};