109-Convert-Sorted-List-to-Binary-Search-Tree
0x0 题目详情
0x1 解题思路
0x2 解题思路
/**
* 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;
}
return recur(head,null);
}
private TreeNode recur(ListNode begin,ListNode end){
if(begin==end){
return null;
}
ListNode fast=begin;
ListNode slow=begin;
while(fast.next!=end && fast.next.next!=end){
fast=fast.next.next;
slow=slow.next;
}
TreeNode root=new TreeNode(slow.val);
root.left=recur(begin,slow);
root.right=recur(slow.next,end);
return root;
}
}0x3 课后总结
Last updated