解题思路:
递归
提交代码:bfs
class Solution {
public TreeNode sortedListToBST(ListNode head) {
// the length of list
int len=0;
ListNode p=head;
while(p!=null) {
p=p.next;
len++;
}
if(len==0) return null;
if(len==1) {
TreeNode node=new TreeNode(head.val);
return node;
}
p=head;
ListNode left=head;
for(int i=0;i<len/2-1;i++)
p=p.next;
ListNode listRoot=p.next;
p.next=null;
TreeNode treeRoot=new TreeNode(listRoot.val);
ListNode right=listRoot.next;
listRoot.next=null;
treeRoot.left=sortedListToBST(left);
treeRoot.right=sortedListToBST(right);
return treeRoot;
}
}
运行结果: