Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
做法是先建树然后中序遍历树并把链的值放进去
public class Solution {
ListNode start;
public TreeNode sortedListToBST(ListNode head) {
int len = 0;
start = head;
while(start!=null){
len++;
start = start.next;
}
TreeNode root = buildTree(len, 1);
start = head;
helper(root);
return root;
}
private TreeNode buildTree(int len, int cur){
if(cur>len) return null;
TreeNode temp = new TreeNode(0);
temp.left = buildTree(len, cur*2);
temp.right = buildTree(len, cur*2 + 1);
return temp;
}
private void helper(TreeNode root){
if(root==null) return;
helper(root.left);
root.val = start.val;
start = start.next;
helper(root.right);
}
}
别人的不断划分长度差为1的两个子段的方法,挺好的
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null) return null;
return toBST(head,null);
}
public TreeNode toBST(ListNode head, ListNode tail){
ListNode slow = head;
ListNode fast = head;
if(head==tail) return null;
while(fast!=tail&&fast.next!=tail){
fast = fast.next.next;
slow = slow.next;
}
TreeNode thead = new TreeNode(slow.val);
thead.left = toBST(head,slow);
thead.right = toBST(slow.next,tail);
return thead;
}
}