【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;
    }
    //找到链表的中间节点作为根节点
}
相关推荐
abant21 小时前
leetcode 114 二叉树变链表
算法·leetcode·链表
XiYang-DING2 小时前
【LeetCode】 225.用队列实现栈
算法·leetcode·职场和发展
派大星~课堂2 小时前
【力扣-148. 排序链表】Python笔记
python·leetcode·链表
小白菜又菜3 小时前
Leetcode 657. Robot Return to Origin
python·leetcode·职场和发展
_深海凉_3 小时前
LeetCode热题100-环形链表
算法·leetcode·链表
memcpy03 小时前
LeetCode 904. 水果成篮【不定长滑窗+哈希表】1516
算法·leetcode·散列表
老四啊laosi3 小时前
[双指针] 8. 四数之和
算法·leetcode·四数之和
田梓燊3 小时前
leetcode 41
数据结构·算法·leetcode
_深海凉_3 小时前
LeetCode热题100-三数之和
算法·leetcode·职场和发展
y = xⁿ4 小时前
【LeetCode】双指针合集
算法·leetcode