【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;
    }
    //找到链表的中间节点作为根节点
}
相关推荐
Adios79411 小时前
设置交集大小至少为2
数据结构·算法·leetcode
程序猿乐锅19 小时前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode
hold?fish:palm1 天前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle1 天前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木1 天前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
啦啦啦啦啦zzzz1 天前
算法:回溯算法
c++·算法·leetcode
小肝一下1 天前
3. 单链表
c语言·数据结构·c++·算法·leetcode·链表·dijkstra
tachibana21 天前
hot100 前 K 个高频元素(347)
java·数据结构·算法·leetcode
To_OC1 天前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎1 天前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题