109. Convert Sorted List to Binary Search Tree

来源:互联网 发布:网络电话隐藏号码软件 编辑:程序博客网 时间:2024/05/28 03:02

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 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) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if(head == NULL)return NULL;        ListNode *fast = head, *slow = head, *preSlow = NULL;        while(fast->next && fast->next->next)        {            fast = fast->next->next;            preSlow = slow;            slow = slow->next;        }        TreeNode *res = new TreeNode(slow->val);        fast = slow->next;        delete slow;        if(preSlow != NULL)        {            preSlow->next = NULL;            res->left = sortedListToBST(head);        }        res->right = sortedListToBST(fast);        return res;    }};


0 0
原创粉丝点击