LeetCode(109):有序链表转换二叉搜索树

Medium!

题目描述:

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

解题思路:

这道题是要求把有序链表转为二叉搜索树,和之前那道Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树思路完全一样,只不过是操作的数据类型有所差别,一个是数组,一个是链表。数组方便就方便在可以通过index直接访问任意一个元素,而链表不行。由于二分查找法每次需要找到中点,而链表的查找中间点可以通过快慢指针来操作,可参见之前的两篇博客Reorder List 链表重排序http://www.cnblogs.com/grandyang/p/4254860.htmlLinked List Cycle II 单链表中的环之二http://www.cnblogs.com/grandyang/p/4137302.html有关快慢指针的应用。找到中点后,要以中点的值建立一个数的根节点,然后需要把原链表断开,分为前后两个链表,都不能包含原中节点,然后再分别对这两个链表递归调用原函数,分别连上左右子节点即可。

C++解法一:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 /**
10  * Definition for binary tree
11  * struct TreeNode {
12  *     int val;
13  *     TreeNode *left;
14  *     TreeNode *right;
15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
16  * };
17  */
18 class Solution {
19 public:
20     TreeNode *sortedListToBST(ListNode *head) {
21         if (!head) return NULL;
22         if (!head->next) return new TreeNode(head->val);
23         ListNode *slow = head;
24         ListNode *fast = head;
25         ListNode *last = slow;
26         while (fast->next && fast->next->next) {
27             last = slow;
28             slow = slow->next;
29             fast = fast->next->next;
30         }
31         fast = slow->next;
32         last->next = NULL;
33         TreeNode *cur = new TreeNode(slow->val);
34         if (head != slow) cur->left = sortedListToBST(head);
35         cur->right = sortedListToBST(fast);
36         return cur;
37     }
38 };

猜你喜欢

转载自www.cnblogs.com/ariel-dreamland/p/9162489.html