给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
思路:
将链表一分为二,取中间元素作为根结点,对左边的链表和右边的链表递归调用转二叉搜索树得到2个子树p1和p2
将根节点的左指针指向p1,右指针指向p2
效率:99.76%
code:
/**
* 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) {
int num = 0;
ListNode *temp = head;
while (temp) {
num++;
temp = temp -> next;
}
if (num == 0)
return NULL;
if (num == 1) {
TreeNode *p = new TreeNode(head -> val);
return p;
}
if (num == 2) {
TreeNode *p = new TreeNode(head -> val);
TreeNode *q = new TreeNode(head -> next -> val);
p -> right = q;
return p;
}
int half = num/2 - 1;
ListNode *t1 = head;
while (half--) {
t1 = t1 -> next;
}
ListNode *t2 = t1 -> next;
t1 -> next = NULL;
TreeNode *p = new TreeNode(t2 -> val);
p -> left = sortedListToBST(head);
p -> right = sortedListToBST(t2 -> next);
return p;
}
};