描述:
給出一個所有元素以升序排序的單鏈表,將它轉換成一棵高度平衡的二分查找樹
樣例:
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;
}
}
};