【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;
    }
    //找到链表的中间节点作为根节点
}
相关推荐
Nil20811 小时前
leetcode 394字符串解码
leetcode
一起努力啊~14 小时前
算法题打卡力扣第1658题:将 x 减到 0 的最小操作数(mid)
学习·leetcode
Cccp.12314 小时前
【leetcode】(六) 图和贪心算法
数据结构·算法·leetcode
y1su14 小时前
【Leetcode】1477. 找两个和为目标值且不重叠的子数组
数据结构·后端·算法·leetcode·职场和发展
mmmmath_31 天前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z1 天前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
参.商.1 天前
【Day 53】76. 最小覆盖子串
leetcode·golang
虚无的纽扣1 天前
【力扣刷题】第二天:无重复字符的最长字串、移动零问题
算法·leetcode·排序算法
圣保罗的大教堂1 天前
leetcode 3742. 网格中得分最大的路径 中等
leetcode
我不会起名字3221 天前
一天一道算法题(35):电话号码的字母组合
java·数据结构·后端·python·leetcode·go·回溯