【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;
    }
    //找到链表的中间节点作为根节点
}
相关推荐
Dream it possible!12 小时前
LeetCode 面试经典 150_链表_旋转链表(64_61_C++_中等)
c++·leetcode·链表·面试
坚持编程的菜鸟14 小时前
LeetCode每日一题——Pow(x, n)
c语言·算法·leetcode
Wenhao.16 小时前
LeetCode LRU缓存
算法·leetcode·缓存·golang
小白菜又菜16 小时前
Leetcode 2273. Find Resultant Array After Removing Anagrams
算法·leetcode·职场和发展
Swift社区16 小时前
LeetCode 409 - 最长回文串 | Swift 实战题解
算法·leetcode·swift
墨染点香19 小时前
LeetCode 刷题【139. 单词拆分】
算法·leetcode·职场和发展
Tisfy1 天前
LeetCode 3346.执行操作后元素的最高频率 I:滑动窗口(正好适合本题数据,II再另某他法)
算法·leetcode·题解·滑动窗口·哈希表
熬了夜的程序员1 天前
【LeetCode】94. 二叉树的中序遍历
数据结构·算法·leetcode·职场和发展·深度优先
熬了夜的程序员1 天前
【LeetCode】92. 反转链表 II
数据结构·算法·leetcode·链表·职场和发展·排序算法
景早1 天前
力扣1. 两数之和
数据结构·算法·leetcode