day81(2.9)——leetcode面试经典150

108. 将有序数组转换为二叉搜索树

108. 将有序数组转换为二叉搜索树

题目:

题解:

java 复制代码
/**
 * 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 {
    TreeNode conTree(int l, int r, int[] nums) { 
        if(l>r) {
            return null;
        }
        int mid = (l+r)/2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left = conTree(l,mid-1,nums);
        node.right = conTree(mid+1,r,nums);
        return node;
    }
    
    public TreeNode sortedArrayToBST(int[] nums) {
        return conTree(0,nums.length-1,nums);
    }
}

148. 排序链表

148. 排序链表

题目:

题解:

java 复制代码
/**
 * 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; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null) {
            return head;
        }
        ListNode cur = head;
        List<Integer> list = new ArrayList<>();
        while(cur!=null) {
            list.add(cur.val);
            cur = cur.next;
        }
        list.sort(null);
        ListNode node = new ListNode();
        cur = node;
        for(int i=0;i<list.size();i++) {
            cur.val=list.get(i);
            if(i!=list.size()-1) {
                cur.next = new ListNode();
            }
            else {
                cur.next = null;
            }
            cur = cur.next;
        }
        return node;
    }
}
相关推荐
漂流瓶jz1 小时前
UVA-1442 洞穴 题解答案代码 算法竞赛入门经典第二版
c++·算法·题解·aoapc·算法竞赛入门经典·uva
圣保罗的大教堂1 小时前
leetcode 835. 图像重叠 中等
leetcode
叠层归一研究院2 小时前
基于极限自指的叠层归一宇宙结构理论——无元外部封闭系统的内生区分模型
人工智能·经验分享·算法·agi
彧azz2 小时前
Linux 网络编程学习总结
linux·网络·笔记·学习·面试
Selvaggia3 小时前
Diffusion Model 的基本原理与模型架构
算法
默_笙4 小时前
💫 闭包是个背包:拆解小米前端面试题里的三道"闭包陷阱"
前端·javascript·面试
wabs6664 小时前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
hanlin034 小时前
刷题笔记:力扣第41题-缺失的第一个正数
笔记·算法·leetcode
shehuiyuelaiyuehao5 小时前
算法50,分治归并,数组中的逆序对
java·算法
DeepAgent5 小时前
AI Agent 入门指南(05):Agent 循环——观察、思考、行动
面试·agent