【LeetCode-树】-- 109.有序链表转换二叉搜索树

109.有序链表转换二叉搜索树

方法:找到链表的中点,将其作为根节点

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; }
 * }
 */
/**
 * 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) {
        return buildTree(head,null);
    }

    public TreeNode buildTree(ListNode left,ListNode right){
        if(left == right){
            return null;
        }
        ListNode mid = getMid(left,right);
        TreeNode root = new TreeNode(mid.val);
        root.left = buildTree(left,mid);
        root.right = buildTree(mid.next,right);
        return root;
    }

    public ListNode getMid(ListNode left,ListNode right){
        ListNode fast = left;
        ListNode slow = left;
        while(fast.next != right && fast.next.next != right){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    //找到链表的中间节点作为根节点
}
相关推荐
py有趣33 分钟前
力扣热门100题之不同路径
算法·leetcode
_日拱一卒1 小时前
LeetCode:25K个一组翻转链表
算法·leetcode·链表
小欣加油1 小时前
leetcode2078 两栋颜色不同且距离最远的房子
数据结构·c++·算法·leetcode·职场和发展
我真不是小鱼1 小时前
cpp刷题打卡记录30——轮转数组 & 螺旋矩阵 & 搜索二维矩阵II
数据结构·c++·算法·leetcode
帅小伙―苏3 小时前
力扣42接雨水
前端·算法·leetcode
6Hzlia3 小时前
【Hot 100 刷题计划】 LeetCode 287. 寻找重复数 | C++ 数组判环 (快慢指针终极解法)
c++·算法·leetcode
穿条秋裤到处跑9 小时前
每日一道leetcode(2026.04.19):下标对中的最大距离
算法·leetcode·职场和发展
木子墨5169 小时前
LeetCode 热题 100 精讲 | 计算几何篇:点积叉积 · 线段相交 · 凸包 · 多边形面积
c++·算法·leetcode·职场和发展·动态规划
py有趣10 小时前
力扣热门100题之最小路径和
算法·leetcode
im_AMBER10 小时前
Leetcode 159 无重复字符的最长子串 | 长度最小的子数组
javascript·数据结构·学习·算法·leetcode