【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;
    }
    //找到链表的中间节点作为根节点
}
相关推荐
历程里程碑13 小时前
普通数组----合并区间
java·数据结构·python·算法·leetcode·职场和发展·tornado
iAkuya13 小时前
(leetcode)力扣100 61分割回文串(回溯,动归)
算法·leetcode·职场和发展
VT.馒头14 小时前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
Charlie_lll15 小时前
力扣解题-移动零
后端·算法·leetcode
iAkuya16 小时前
(leetcode)力扣100 62N皇后问题 (普通回溯(使用set存储),位运算回溯)
算法·leetcode·职场和发展
YuTaoShao21 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
TracyCoder1231 天前
LeetCode Hot100(27/100)——94. 二叉树的中序遍历
算法·leetcode
草履虫建模1 天前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
VT.馒头1 天前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript
不穿格子的程序员2 天前
从零开始写算法——普通数组篇:缺失的第一个正数
算法·leetcode·哈希算法