leetcode——109——Convert Sorted List to Binary Search Tree

来源:互联网 发布:人工智能战机 编辑:程序博客网 时间:2024/06/06 07:23

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

/** * 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;}if (head->next == NULL)return new TreeNode(head->val);ListNode* mid = findMid(head);TreeNode* root = new TreeNode(mid->val);root->left = sortedListToBST(head);root->right = sortedListToBST(mid->next);return root;}ListNode* findMid(ListNode* head){ListNode* preslow = NULL;ListNode* slow = head;ListNode* fast = head;while (fast != NULL){fast = fast->next;if (fast != NULL){fast = fast->next;preslow = slow;slow = slow->next;}}preslow->next = NULL;return slow;}};

0 0