安卓下载软件app,谷歌seo博客,个人做外贸网站违法吗,保险官网查询力扣#xff08;LeetCode#xff09;官网 - 全球极客挚爱的技术成长平台 给定一个单链表的头节点 head #xff0c;其中的元素 按升序排序 #xff0c;将其转换为高度平衡的二叉搜索树。 本题中#xff0c;一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度… 力扣LeetCode官网 - 全球极客挚爱的技术成长平台 给定一个单链表的头节点 head 其中的元素 按升序排序 将其转换为高度平衡的二叉搜索树。 本题中一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。 代码如下
class Solution {public TreeNode sortedListToBST(ListNode head) {if(head null){return null;}//左开右闭return helper(head,null);}private TreeNode helper(ListNode head,ListNode tail){if(head tail){return null;}ListNode slow head;ListNode fast head;while(fast ! tail fast.next ! tail){slow slow.next;fast fast.next.next;}TreeNode root new TreeNode(slow.val);root.left helper(head,slow);root.right helper(slow.next,tail);return root;}
}