【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;
    }
    //找到链表的中间节点作为根节点
}
相关推荐
文丑颜不良啊4 小时前
LeetCode1941~1960题目解析
java·leetcode
文丑颜不良啊8 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊9 小时前
LeetCode2001~2020题目解析
java·leetcode
文丑颜不良啊12 小时前
LeetCode2021~2040题目解析
java·leetcode
Nuanyt1 天前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
圣保罗的大教堂1 天前
leetcode 3736. 最小操作次数使数组元素相等 III 简单
leetcode
文丑颜不良啊1 天前
LeetCode1881~1990题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode1861~1880题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode1921~1940题目解析
java·leetcode