【LeetCode】 109. Convert Sorted List to Binary Search Tree 有序链表转换二叉搜索树(Medium)(JAVA)
题目地址: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
题目描述:
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
题目大意
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
解题方法
1、和上一题类似,只是不像数组,可以知道长度和某个位置的元素 【LeetCode】 108. Convert Sorted Array to Binary Search Tree 将有序数组转换为二叉搜索树(Easy)(JAVA)
2、采用快慢指针,找出中间节点
3、采用递归
/**
* 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; }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
if (head.next == null) return new TreeNode(head.val);
ListNode slow = head;
ListNode fast = head.next.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.next.val);
ListNode right = slow.next.next;
slow.next = null;
root.left = sortedListToBST(head);
root.right = sortedListToBST(right);
return root;
}
}
执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 40.5 MB, 在所有 Java 提交中击败了 13.33% 的用户