[leetcode 16] convert-sorted-list-to-binary-search-tree

17 篇文章 0 订阅

题目描述
给定一个单链表,其中的元素按升序排序,请将它转化成平衡二叉搜索树(BST)

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced 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 == nullptr)
            return nullptr;
        TreeNode *root = new TreeNode(0);
        BSTHelper(root, head);
        return root;
    }
    
    void BSTHelper(TreeNode *node, ListNode *head)
    {
        ListNode *fast = head;
        ListNode *low = head;
        ListNode *prelow;
        while (fast != nullptr && fast->next != nullptr)
        {
            fast = fast->next->next;
            prelow = low;
            low = low->next;
        }
        node->val = low->val;
        if (low != head)
        {
            prelow->next = nullptr;
            node->left = new TreeNode(0);
            BSTHelper(node->left, head);
        }
        if (low->next != nullptr)
        {
            ListNode *tmp = low->next;
            low->next = nullptr;
            node->right = new TreeNode(0);
            BSTHelper(node->right, tmp);
        }
        return;
    }
};

代码没有很简洁,但是思路很清晰,简洁版的如下:

class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        if (head == nullptr) return nullptr;
        if (head->next == nullptr) return new TreeNode(head->val);
        ListNode dummy = ListNode(0);
        dummy.next = head;
        ListNode* p2 = &dummy;
        ListNode* p1 = &dummy;
        while (p2->next&&p2->next->next) {
            p2 = p2->next->next;
            p1 = p1->next;
        }
        TreeNode *root = new TreeNode(p1->next->val);
        p2 = p1->next->next;
        p1->next = nullptr;
        root->left = sortedListToBST(dummy.next);
        root->right = sortedListToBST(p2);
        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值