109有序链表转换二叉搜索树 Posted on 2020-04-19 Words count in article: 418 | Reading time ≈ 2 109. 有序链表转换二叉搜索树 下面是题目给出的模板12345678910111213141516171819202122/** * 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) { }; 对于这题,最简单的就是递归构建树123456789101112131415161718192021222324252627//首先我们写一个构造树的函数,通过递归来实现。 //然后用vector存储链表,用来构建树//因为已经是升序链表了,所以没必要再排序,如果是无序链表构建二叉搜索树,我们需要对vector进行再排序class Solution {public: TreeNode* sortedListToBST(ListNode* head) { vector<int> v; //建立一个数组来存储所有的数据 ListNode *cur = head; while(cur) { v.push_back(cur->val); cur = cur->next; } //用递归来解决 return buildTree(v,0,v.size()); } TreeNode* buildTree(vector<int> v,int begin,int end) { if(begin==end)return NULL; int middle = (begin+end)/2; TreeNode *root = new TreeNode(v[middle]); root->left = buildTree(v,begin,middle); root->right = buildTree(v,middle+1,end); return root; }}; 但是上面这种方法消耗了很多时间和空间,能不能用更快的方法呢?1234567891011121314151617181920212223 [-10, -3, 0, 5, 9]class Solution {public: TreeNode* sortedListToBST(ListNode* head) { if (!head) return 0; ListNode* p = head; ListNode* q = p; ListNode* pre = 0; //利用快慢指针,找到链表的中间节点 while (q && q->next) { q = q->next->next; pre = p; p = p->next; } //这时候,pre是p的前驱,pre为-3,p为0 if (pre) pre->next = 0; TreeNode* root = new TreeNode(p->val); node->left = sortedListToBST(head == p ? pre : head); node->right = sortedListToBST(p->next);//继续递归 return root; }}; -------------本文结束,感谢您的阅读------------- Post author: Jason Post link: https://jasonxqh.github.io/2020/04/19/109%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8%E8%BD%AC%E6%8D%A2%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91/ Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.