将一个顺序链表转换成一棵二叉树
利用快慢指针,快指针比满指针每次多走一步
slow = slow->next;
fast = fast->next->next;
快指针走到尾,满指针走到中间点,中间点作为二叉树的根节点root,
root前的节点为左子树,root后的节点为右子树,递归
TreeNode* BST(ListNode* head, ListNode* tail)
{
if (head == tail)
return NULL;
ListNode* slow = head;
ListNode* fast = head;
while (fast != tail && fast->next != tail)
{
slow = slow->next;
fast = fast->next->next;
}
if (fast->next != tail)
{
slow = slow->next;
}
TreeNode* root = new TreeNode(slow->val);
root->left = BST(head, slow);
root->right = BST(slow->next, tail);
return root;
}
TreeNode* sortedListToBST(ListNode *head)
{
if (head == NULL)
return NULL;
else
return BST(head, NULL);
}