和LeetCode 108. Convert Sorted Array to Binary Search Tree
给定升序链表,构造平衡查找二叉树。
用slow, fast指针将链表分成两条即可。
代码:
class Solution
{
public:
TreeNode *sortedListToBST(ListNode *head)
{
if (head == NULL)
{
return NULL;
}
ListNode *pre=NULL, *slow=head, *fast=head;
while (fast->next!=NULL && fast->next->next!=NULL)
{
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
TreeNode *tree = new TreeNode(slow->val);
if (pre != NULL)
{
pre->next = NULL;
tree->left = sortedListToBST(head);
} else
{
tree->left = NULL;
}
tree->right = sortedListToBST(slow->next);
return tree;
}
};