1、使用递归方法将LingkedList转换成平衡二叉树
1)获取LinkedList长度
private int getListLength(ListNode head) {
int size = 0;
while (head != null) {
size++;
head = head.next;
}
return size;
}
2)递归生成二叉树
public TreeNode sortedListToBSTHelper(int size) {
if (size <= 0) {
return null;
}
TreeNode left = sortedListToBSTHelper(size / 2);
TreeNode root = new TreeNode(current.val);
current = current.next;
TreeNode right = sortedListToBSTHelper(size - 1 - size / 2);
root.left = left;
root.right = right;
return root;
}
3)
public TreeNode sortedListToBST(ListNode head) {
int size;
current = head;
size = getListLength(head);
return sortedListToBSTHelper(size);
}