题目大意:给出升序链表,根据它构建平衡二叉搜索树。
分析:链表和dfs的考察。和leetcode108类似,找到链表的中间结点也就是根节点然后递归分别构建左右子树。注意巧妙的用快慢指针找到链表中间节点这一方法。
代码:转载自https://www.cnblogs.com/hellowooorld/p/6624709.html
TreeNode* sortedListToBST(ListNode* head) {
//利用fast 和 slow 指针 找到链表中点
return build(head,NULL);
}
TreeNode* build(ListNode* start, ListNode* end) {
if (start == end) { //end是结束标志,不在搜索范围内,所以遇到end就返回NULL
return NULL;
}
ListNode* fast = start;
ListNode* slow = start; //最终指向链表中间节点
while (fast != end && fast->next != end)//注意第一次执行的时候end为NULL 没毛病。。
{
fast = fast->next->next;
slow = slow->next;
}
TreeNode* node = new TreeNode(slow->val);
node->left = build(start, slow);
node->right = build(slow->next, end);
return node;
}