描述:
给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树
样例:
2
1->2->3 => / \
1 3
思路:
折半取链表中的元素作为其根节点,左半部分作为其左子树,右半部份作为其右子树。不断递归。
相比于数组转换二叉查找树,多了些链表的遍历而已。
AC代码:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
TreeNode *sortedListToBST(ListNode *head) {
// write your code here
if(head==NULL)
return NULL;
int lenth=0;
ListNode*pr=head;
while(pr!=NULL)
{
lenth++;
pr=pr->next;
}
if(lenth==1)
return new TreeNode(head->val);
else
{
lenth/=2;
int i=0;
pr=head;
while(i<lenth-1)
{
pr=pr->next;
i++;
}
TreeNode*root=new TreeNode(pr->next->val);
root->right=sortedListToBST(pr->next->next);
pr->next=NULL;
root->left=sortedListToBST(head);
return root;
}
}
};