LeetCode 109. Convert Sorted List to Binary Search Tree

来源:互联网 发布:项目数据分析师 上海 编辑:程序博客网 时间:2024/06/07 03:48

和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;    }};


0 0