1、前言
题目描述
2、思路
可以采用将有序数转化为二叉搜索树的思路,只不过链表找节点使用的快慢指针,最后的 slow 就是中点,然后基于 [head, slow] 根 [slow + 1, tail] 两部分递归。
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;
}
// 尾节点为 null
return dfs(head, null);
}
private TreeNode dfs(ListNode head, ListNode tail){
if(head == tail){
return null;
}
ListNode slow = head;
ListNode fast = head;
// 关于这一点,fast 是不等于 tail,注意
while(fast != tail && fast.next != tail){
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = dfs(head, slow);
root.right = dfs(slow.next, tail);
return root;
}
}








网友评论