LeetCode-Convert Sorted List to Binary Search Tree

来源:互联网 发布:java导出excel 进度条 编辑:程序博客网 时间:2024/06/05 00:54

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

Solution:

Code:

<span style="font-size:14px;">/** * 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) {        if (!head) return NULL;        if (!head->next) return new TreeNode(head->val);        ListNode *fast = head->next->next, *slow = head;        while (fast && fast->next) {            fast = fast->next->next;            slow = slow->next;        }        fast = slow->next;        slow->next = NULL;        TreeNode *root = new TreeNode(fast->val);        root->left = sortedListToBST(head);        root->right = sortedListToBST(fast->next);        return root;    }};</span>


0 0
原创粉丝点击