编程练习:链表习题(下)

(6)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.

思路:
(1)分析题意:要求将一条有序链表转化为一颗二叉搜索树
(2)快慢指针法找到链表的中点
(3)以中点的值建立一个树的根节点
(4)从中间节点将原链表分为两条子链表
(5)分别对两个链表递归调用原函数

代码实现:

class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        if(head == NULL)
            return NULL;
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* ret = NULL;
        while(fast!=NULL&&fast->next!=NULL)
        {
            fast = fast->next->next;
            ret = slow;
            slow = slow->next;
        }
        TreeNode* root = new TreeNode(slow->val);//找到中间节点作为根节点
        if(ret != NULL)
        {
            ret->next = NULL;
            root->left = sortedListToBST(head);
        }
        if(slow->next != NULL)
        {
            root->right = sortedListToBST(slow->next);
        }
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/zjx624bjh/article/details/81454321