[LeetCode]109. Convert Sorted List to Binary Search Tree

来源:互联网 发布:tomcat java options 编辑:程序博客网 时间:2024/06/17 07:04

[LeetCode]109. Convert Sorted List to Binary Search Tree

题目描述

这里写图片描述

思路

和 [LeetCode]108. Convert Sorted Array to Binary Search Tree 问题思路相同,只是数据结构从数组变成了链表,找到链表重点的方法,需要用快慢指针

代码

#include <iostream>#include <vector>using namespace std;struct ListNode {    int val;    ListNode* next;    ListNode(int x) : val(x), next(NULL) {}};struct TreeNode {    int val;    TreeNode* left;    TreeNode* right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:    ListNode* vectorToList(vector<int> nums) {        if (nums.size() == 0)            return NULL;        ListNode *head = new ListNode(nums[0]),            *iter = head;        for (int i = 1; i < nums.size(); ++i) {            ListNode *temp = new ListNode(nums[i]);            iter->next = temp;            iter = iter->next;        }        return head;    }    TreeNode* sortedListToBST(ListNode* head) {        return insert(head, NULL);    }    TreeNode* insert(ListNode* head, ListNode* tail) {        if (head == NULL || head == tail || (tail && tail->next == head))            return NULL;        ListNode *slow = head, *fast = head;        while (fast != tail) {            if (fast == tail || fast->next == tail)                break;            slow = slow->next;            fast = fast->next->next;        }        TreeNode *root = new TreeNode(slow->val);        root->left = insert(head, slow);        root->right = insert(slow->next, tail);        return root;    }    void visit(TreeNode* root) {        if (root == NULL)            return;        if (root->left)            visit(root->left);        cout << root->val << " ";        if (root->right)            visit(root->right);    }};int main() {    vector<int> nums = { 1,2,3,4,5,6,7 };    Solution s;    ListNode *head = s.vectorToList(nums);    TreeNode *root = s.sortedListToBST(head);    s.visit(root);    cout << endl;    system("pause");    return 0;}
0 0
原创粉丝点击