ð 109. æåºéŸè¡šèœ¬æ¢äºåæ玢æ
2022幎10æ10æ¥
- algorithm
ð 109. æåºéŸè¡šèœ¬æ¢äºåæ玢æ
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
// æè·¯ïŒ
// å¿«æ
¢æéæŸäžç¹ïŒå¯¹äžç¹è¿è¡æå
return mySol(head);
}
private TreeNode mySol(ListNode head) {
// éåœç»æ¢æ¡ä»¶
if(head == null) {
return null;
}
if(head.next == null) {
return new TreeNode(head.val);
}
ListNode pre = getMid(head); // äžç¹åå·Š
ListNode mid;
if(pre == null) {
// éŸè¡šåªæ 2 䞪èç¹
mid = head;
} else {
mid = pre.next;
pre.next = null;
}
ListNode next = mid.next;
mid.next = null;
TreeNode root = new TreeNode(mid.val);
// System.out.println(root.val);
if(pre != null) {
root.left = mySol(head);
}
root.right = mySol(next);
return root;
}
private ListNode getMid(ListNode head) {
ListNode pre = null;
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null) {
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
return pre; // åŸå°åå·Šäžç¹åé¢çèç¹
}
}