leetcode-109-Convert Sorted List to Binary Search Tree

本文介绍如何将一个按升序排列的单链表转换为高度平衡的二叉搜索树(BST)。通过自底向上地构建树结构,确保了树的高度平衡特性。文章提供了完整的C++实现代码。
#include <iostream>
using namespace std;
/*
 题目要求:
 Given a singly linked list where elements are 
 sorted in ascending order, convert it to a height 
 balanced BST.
 这道题可以与108的根据有序数组构建平衡二叉搜索树作对比,由于有序数组可以
 随机访问元素,所以108那道题可以用自顶向下的方法构建树。但是单链表不能随机
 访问,只能顺序访问,根据这个数据结构的特点,自顶向下的建树顺序不太妥当,应当
 用自底向上的建树顺序,从左向右扫描链表,由于比中间数字小的数字都是该数字的左子树,
 所以可以先构建所有可能的右子树,然后构建中间数字的节点,再考虑其右子树。
 */
/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        int len = 0;
        ListNode* cur = head;
        while (cur) {
            cur = cur->next;
            len++;
        }
        return bottomUp(head, 0, len - 1);
    }
private:
    //注意要用引用参数
    TreeNode* bottomUp(ListNode* &h, int left, int right){
        //如果链表为空,则返回空指针
        if (!h) {
            return NULL;
        }
        if (left > right) {
            return NULL;
        }
        int mid = (left + right) / 2;
        //构建左子树
        TreeNode* lChild = bottomUp(h, left, mid - 1);
        //当前节点
        TreeNode* current = new TreeNode(h->val);
        current->left = lChild;
        h = h->next;
        //构建右子树
        TreeNode* rChild = bottomUp(h, mid + 1, right);
        current->right = rChild;
        return current;
    }
};
int main(int argc, const char * argv[]) {
    ListNode one(1);
    ListNode two(2);
    ListNode three(3);
    one.next = &two;
    two.next = &three;
    Solution s;
    TreeNode *res = s.sortedListToBST(&one);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值