力扣0109——有序链表转换二叉搜索树

有序链表转换二叉搜索树

难度:中等

题目描述

给定一个单链表的头节点 head ,其中的元素 按升序排序 ,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。

示例1:

输入: head = [-10,-3,0,5,9]
输出: [0,-3,9,-10,null,5]
解释: 一个可能的答案是[0,-3,9,-10,null,5],它表示所示的高度平衡的二叉搜索树。

示例2:

输入: head = []
输出: []

题解:

0108一样的思路,将链表中的元素转存到数组中,之后按照 0108 的思路解题即可

想法代码

using System;
using System.Collections;
using System.Collections.Generic;

public class ListNode
{
    public int val;
    public ListNode next;

    public ListNode(int val = 0, ListNode next = null)
    {
        this.val = val; 
        this.next = next;
    }
}

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this .val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution
{
    public static void Main(string[] args)
    {
        ListNode list = new ListNode
        {
            val = -10,
            next = new ListNode
            {
                val = -3,
                next = new ListNode
                {
                    val = 0,
                    next = new ListNode
                    {
                        val = 5,
                        next = new ListNode
                        {
                            val = 9
                        }
                    }
                }
            }
        };
        Solution solution = new Solution();
        TreeNode ans = solution.SortedListToBST(list);
        Console.ReadKey();
    }

    public TreeNode SortedListToBST(ListNode head)
    {
        Queue<int> queue = new Queue<int>();
        int index = 0;
        while (head != null)
        {
            queue.Enqueue(head.val);
            head = head.next;
        }
        int[] temp = new int[queue.Count];
        while (queue.Count > 0)
        {
            temp[index] = queue.Dequeue();
            index++;
        }

        return BackTrack(temp, 0, temp.Length - 1);
    }

    public TreeNode BackTrack(int[] nums, int start, int end)
    {
        if (start > end)
        {
            return null;
        }
        int mid = (start + end) / 2;
        return new TreeNode(nums[mid], BackTrack(nums, start, mid - 1), BackTrack(nums, mid + 1, end));
    }
}
  • 29
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值