【convert-sorted-list-to-binary-search-tree】

来源:互联网 发布:达芬奇家具造假 知乎 编辑:程序博客网 时间:2024/06/09 13:05

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


题意;将排序链表转换成平衡二叉树;

每次取中间节点,自然就是平衡二叉树了;

思路:自顶向下递归解决,先找到中间节点作为根节点,然后递归左右两部分,所以我们先需要连找到中间节点,对于单链表来说,

必须要遍历一遍,可以使用快慢指针加速查找速度;

class Solution {public:TreeNode* sortedListToBST(ListNode* head){if (head==NULL){return NULL;}//用快慢指针来找中间节点ListNode* slow = head;ListNode* fast = head;ListNode* preSlow = NULL;while (fast!=NULL && fast->next!=NULL){preSlow = slow;slow = slow->next;fast = fast->next->next;}TreeNode* mid = new TreeNode(slow->val);//分别递归左右部分if (preSlow!=NULL){preSlow->next = NULL;mid->left = sortedListToBST(head);}if (slow->next!=NULL){mid->right = sortedListToBST(slow->next);}return mid;}};



原创粉丝点击