摘要:题目答案这里是不能等于也省去了把从中间分隔时,需要添加的麻烦
题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
答案:
</>复制代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode BST(ListNode head, ListNode tail) {
ListNode slow = head, fast = head;
if (head == tail) return null;
//这里是fast不能等于tail,也省去了把listnode从中间分隔时,需要添加null的麻烦!
while (fast != tail && fast.next != tail) {
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = BST(head, slow);
root.right = BST(slow.next, tail);
return root;
}
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
return BST(head, null);
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/64921.html
摘要:题目要求给一个按照递增顺序排列的链表。将该链表转化为平衡二叉树。思路和代码在这里需要注意的是,因为提供的数据结构为链表,所以我们必须顺序遍历才能知道该链表的长度以及该链表的中间位置。并依次递归左子节点和右子节点。 题目要求 Given a singly linked list where elements are sorted in ascending order, convert i...
Problem Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in whi...
摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...
摘要:自己没事刷的一些的题目,若有更好的解法,希望能够一起探讨项目地址 自己没事刷的一些LeetCode的题目,若有更好的解法,希望能够一起探讨 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...
摘要:我们可以用和两个值来限定子树在链表中的位置,通过递归的方式,深入找到最左边,然后开始顺序遍历链表链表当前节点作为全局变量,这样无论递归在哪我们都能拿到,同时建树。代码先递归的计算左子树创造根节点最后递归的计算右子树 Convert Sorted List to Binary Search Tree Given a singly linked list where elements ar...
阅读 798·2023-04-26 01:42
阅读 3318·2021-11-22 11:56
阅读 2521·2021-10-08 10:04
阅读 994·2021-09-24 10:37
阅读 3252·2019-08-30 15:52
阅读 1963·2019-08-29 13:44
阅读 592·2019-08-28 17:51
阅读 2255·2019-08-26 18:26