每日一题算法:2020年8月18日[有序链表转换二叉搜索树]sortedListToBST

这篇博客介绍了如何将有序链表转化为二叉搜索树,关键在于保持树的平衡,通过选取链表的中值作为根节点,再递归处理剩余部分。解题思路涉及二分法思想,需要自定义处理链表并实现递归代码。
摘要由CSDN通过智能技术生成

2020年8月18日有序链表转换二叉搜索树sortedListToBST

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        
    }
}

解题思路:

本题的关键在于要保证二叉树是平衡的,那么我们构建一颗平衡搜索树肯定是有顺序的,而这个顺序应该就是有序链表的中间值的顺序。我们保证每一次取出的都是中值就能构建一颗平衡搜索树。就和所谓的二分搜索法差不多的道理。

具体的做法是使用递归,我们先取出中值,来构建这一个节点,并且把分出的两部分进行递归,生成左右两个子节点。

问题:这里给的链表不是Java工具类中的List,而是自己定义的一个List对象,这样的话我们需要自己对这个List进行处理。

代码实现:
在这里插入图片描述

    ArrayList<Integer> array=new ArrayList<>();
    public TreeNode sortedListToBST(ListNode head) {

        //第一步,构建链表
        if (head==null)
            return null;
        else
            array.add(head.val);

        while (head.next!=null){
            head=head.next;
            array.add(head.val);
        }


        //构建链表后,进行递归操作


        return buildTree(0, array.size()-1);
    }

    public TreeNode buildTree(int startIndex,int endIndex){
        
        //如果长度为0,则表示节点为null
        if (endIndex-startIndex<0){
            return null;
        }
        
        TreeNode node=new TreeNode(array.get((startIndex+endIndex)/2));

        
        
        node.left=buildTree(startIndex,(startIndex+endIndex)/2-1);
        node.right=buildTree((startIndex+endIndex)/2+1,endIndex);
        
        return node;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值