Medium!

题目描述:

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

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

示例:

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

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

      0
     / \
   -3   9
   /   /
 -10  5

解题思路:

这道题是要求把有序链表转为二叉搜索树,和之前那道Linked 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 };

 

相关文章:

  • 2021-12-17
  • 2022-02-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-07
猜你喜欢
  • 2021-04-07
  • 2022-12-23
  • 2021-09-10
  • 2021-10-12
  • 2021-12-31
  • 2021-08-20
  • 2021-10-23
相关资源
相似解决方案