Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
» Solve this problemComplexity: O(n^2)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *sortedListToBST(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = 0; ListNode *node = head; while (node) { ++n; node = node->next; } return toBST(head, n); } // n - the total number of nodes needs processing TreeNode *toBST(ListNode *head, int n) { if (!head || n <= 0) return NULL; int mid = n / 2; ListNode *midNode = head; for (int i = 0; i < mid; ++i) { midNode = midNode->next; } TreeNode *root = new TreeNode(midNode->val); root->left = toBST(head, mid); root->right = toBST(midNode->next, n - mid - 1); return root; } };
No comments:
Post a Comment