1.题目描述
109. Convert Sorted List to Binary Search Tree
Medium
73355FavoriteShare
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
给一个上升序列,构造一个“高度平衡”二叉搜索树。所谓“高度平衡”二叉搜素树是指任意一个结点的两个子树高度差不可以大于1.
2.解题思路
递归解法比较明显。因为是一个上升序列,所以以中位数为根,左边构造左子树,右边构造右子树即可。稍微需要思考的地方是怎么找这个中位数。上升序列是以链表的形式给出的。看到的一个比较巧妙的方法是两个指针同时从链表头出发,一个每次走两步,另外一个每次走一步。那么走得快的那个到达尾部的时候,走得慢的那个正好在中间,这样就确定了中位数的位置。对前半部分和后半部分进行递归即可。
3.实现代码
/**
* 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)
{
return sortedListToBST( head, NULL );
}
TreeNode *sortedListToBST(ListNode *head, ListNode *tail)
{
if( head == tail )
return NULL;
if( head->next == tail ) {
TreeNode *root = new TreeNode( head->val );
return root;
}
ListNode *mid = head, *temp = head;
while( temp != tail && temp->next != tail ) {// 寻找中间节点,mid走一步,temp走两步,那么temp到达终点的时候mid就是中点了
mid = mid->next;
temp = temp->next->next;
}
TreeNode *root = new TreeNode( mid->val );
root->left = sortedListToBST( head, mid );
root->right = sortedListToBST( mid->next, tail );
return root;
}
};