首页 > 代码库 > 【LeetCode】Convert Sorted List to Binary Search Tree

【LeetCode】Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

 

为了满足平衡要求,容易想到提出中间节点作为树根,因为已排序,所以左右两侧天然满足BST的要求。

左右子串分别递归下去,上层根节点连接下层根节点即可完成。

详见代码与注释。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode *sortedListToBST(ListNode *head) {        if(head == NULL)        {//            return NULL;        }        else if(head->next == NULL)        {//一个节点            TreeNode* root = new TreeNode(head->val);            return root;        }        else        {            ListNode* mid = findMid(head);  //找出中间节点作为根节点(满足保持平衡的要求)            ListNode* lefthead = head;      //左子串头节点为原链表头节点            ListNode* righthead = mid->next;//右子串头节点为中间节点的下一个节点            TreeNode* root = new TreeNode(mid->val);    //递归下去即可            root->left = sortedListToBST(lefthead);            root->right = sortedListToBST(righthead);            return root;        }    }    ListNode* findMid(ListNode* head)    {//调用前提是head != NULL     //若链表为偶数,则返回均分后半子串的指针;若链表为奇数,则返回中间节点的指针        ListNode* pre = NULL;        ListNode* fast = head;        ListNode* slow = head;        while(fast != NULL)        {            fast = fast->next;            if(fast != NULL)            {                fast = fast->next;                pre = slow;                slow = slow->next;            }        }        pre->next = NULL;   //前子串尾部置空        return slow;    }};

【LeetCode】Convert Sorted List to Binary Search Tree