力扣:109. 有序链表转换二叉搜索树

This commit is contained in:
huangge1199 2021-02-09 14:35:24 +08:00
parent da94ad6594
commit 580b0b0b31

View File

@ -0,0 +1,53 @@
package com.code.leet.study.t20210209;
import com.code.leet.entiy.ListNode;
import com.code.leet.entiy.TreeNode;
/**
* 给定一个单链表其中的元素按升序排序将其转换为高度平衡的二叉搜索树
* <p>
* 本题中一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1
* <p>
* 示例:
* <p>
* 给定的有序链表 [-10, -3, 0, 5, 9],
* <p>
* 一个可能的答案是[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树
* <p>
* 0
* / \
* -3 9
* / /
* -10 5
* <p>
* 来源力扣LeetCode
* 链接https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
* 著作权归领扣网络所有商业转载请联系官方授权非商业转载请注明出处
*/
public class SortedListToBST {
/**
* 109. 有序链表转换二叉搜索树
*/
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
} else if (head.next == null) {
return new TreeNode(head.val);
}
ListNode beforeMid = head;
ListNode mid = head;
ListNode last = head;
while (last != null && last.next != null) {
beforeMid = mid;
mid = mid.next;
last = last.next.next;
}
beforeMid.next = null;
TreeNode root = new TreeNode(mid.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(mid.next);
return root;
}
}