109. Convert Sorted List to Binary Search Tree
by Botao Xiao
Question
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
Thinking:
- Method 1:递归, 双指针
- 这道题的思想其实是和108. Convert Sorted Array to Binary Search Tree想法是一致的。
- 通过双指针的找到链表的中点。
- 递归将结点一个个赋值到二叉查找树中。
/**
* 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;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
ListNode pre = null;
while(fast != null && fast.next != null){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
TreeNode ret = new TreeNode(slow.val);
ret.left = sortedListToBST(dummy.next);
ret.right = sortedListToBST(slow.next);
return ret;
}
}
二刷
有一个疑惑,当node.left = sortedListToBST(dummy.next);中的dummy.next改成head时就会爆栈。
/**
* 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;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = null;
ListNode slow = dummy;
ListNode fast = dummy;
while(fast != null && fast.next != null){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
TreeNode node = new TreeNode(slow.val);
node.left = sortedListToBST(dummy.next);
node.right = sortedListToBST(slow.next);
return node;
}
}
Subscribe via RSS