將有序鏈表轉換爲二叉搜索樹>>>
採用二分查找法
:和數組的類似,將鏈表分爲兩部分,左邊的爲左子樹,右邊的爲右子樹
`package JDFS;
import java.util.ArrayList;
import java.util.List;
public class Problem109 {
public TreeNode sortedListToBST(ListNode head) {
if(head==null) return null;
return dfs(head,null);
}
public TreeNode dfs(ListNode head,ListNode tail){
if(head==tail) return null;
ListNode slow = head;
ListNode quick = head;
while(quick!=tail&&quick.next!=tail){
quick=quick.next.next;
slow=slow.next;
}
TreeNode node = new TreeNode(slow.val);
node.left=dfs(head,slow);
node.right=dfs(slow.next,tail);
return node;
}
public TreeNode sortedListToBST1(ListNode head) {
List<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
return helper(list,0,list.size()-1);
}
private TreeNode helper(List<Integer> list, int lo, int hi) {
if(lo > hi) return null;
int mid = lo + (hi-lo)/2;
TreeNode root = new TreeNode(list.get(mid));
root.left = helper(list,lo,mid-1);
root.right = helper(list,mid+1,hi);
return root;
}
}