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;
    }
}
相关推荐
寻寻觅觅☆8 小时前
东华OJ-基础题-106-大整数相加(C++)
开发语言·c++·算法
m0_607076608 小时前
CSS3 转换,快手前端面试经验,隔壁都馋哭了
前端·面试·css3
偷吃的耗子8 小时前
【CNN算法理解】:三、AlexNet 训练模块(附代码)
深度学习·算法·cnn
NEXT069 小时前
二叉搜索树(BST)
前端·数据结构·面试
化学在逃硬闯CS9 小时前
Leetcode1382. 将二叉搜索树变平衡
数据结构·算法
NEXT069 小时前
JavaScript进阶:深度剖析函数柯里化及其在面试中的底层逻辑
前端·javascript·面试
ceclar1239 小时前
C++使用format
开发语言·c++·算法
Gofarlic_OMS10 小时前
科学计算领域MATLAB许可证管理工具对比推荐
运维·开发语言·算法·matlab·自动化
夏鹏今天学习了吗10 小时前
【LeetCode热题100(100/100)】数据流的中位数
算法·leetcode·职场和发展
忙什么果11 小时前
上位机、下位机、FPGA、算法放在哪层合适?
算法·fpga开发