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 which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/
-3 9
/ /
-10 5
Solution
class Solution {
public TreeNode sortedListToBST(ListNode head) {
return helper(head, null);
}
private TreeNode helper(ListNode head, ListNode tail) {
if (head == tail) return null;
ListNode fast = head, slow = head;
while (fast != tail && fast.next != tail) {
fast = fast.next.next;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = helper(head, slow);
root.right = helper(slow.next, tail);
return root;
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72186.html
摘要:题目要求给一个按照递增顺序排列的链表。将该链表转化为平衡二叉树。思路和代码在这里需要注意的是,因为提供的数据结构为链表,所以我们必须顺序遍历才能知道该链表的长度以及该链表的中间位置。并依次递归左子节点和右子节点。 题目要求 Given a singly linked list where elements are sorted in ascending order, convert i...
摘要:我们可以用和两个值来限定子树在链表中的位置,通过递归的方式,深入找到最左边,然后开始顺序遍历链表链表当前节点作为全局变量,这样无论递归在哪我们都能拿到,同时建树。代码先递归的计算左子树创造根节点最后递归的计算右子树 Convert Sorted List to Binary Search Tree Given a singly linked list where elements ar...
摘要:题目答案这里是不能等于也省去了把从中间分隔时,需要添加的麻烦 题目:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 答案: /** * Definition for singly-linked list. * p...
摘要:思路根据的性质,问题转化为找一个里的中位数,用一个函数,一路找中点,再通过前序遍历的方法把起来代码 Convert Sorted Array to Binary Search Tree With Minimal Height Given a sorted (increasing order) array, Convert it to create a binarytree with m...
摘要:解题思路平衡二叉树,其实就是数组中间的数作为根,利用递归实现左子树和右子树的构造。 Convert Sorted Array to Binary Search TreeGiven an array where elements are sorted in ascending order, convert it to a height balanced BST. 1.解题思路平衡二叉树,...
阅读 3892·2021-11-25 09:43
阅读 3273·2021-11-25 09:43
阅读 4161·2021-11-24 09:38
阅读 902·2021-11-18 10:02
阅读 2474·2021-09-22 15:53
阅读 3236·2019-08-30 15:44
阅读 2937·2019-08-30 14:01
阅读 3157·2019-08-29 15:15