[leetcode] 109. 有序链表转换二叉搜索树
这个题和上个题108. 将有序数组转换为二叉搜索树唯一的区别就是数字变成了链表,所以一个比较直观的做法就是先遍历一遍链表。。。。233
class Solution {
public TreeNode sortedListToBST(ListNode head) {
ArrayList<Integer> list = new ArrayList<>();
while (head!=null){
list.add(head.val);
head=head.next;
}
if (list.size()==0) return null;
return sortedArrayToBST(list);
}
public TreeNode sortedArrayToBST(List<Integer> nums) {
int index = nums.size() / 2;
TreeNode treeNode = new TreeNode(nums.get(index));
if (index > 0) {
treeNode.left = sortedArrayToBST(nums.subList(0, index));
}
if (nums.size() - index - 1 > 0) {
treeNode.right = sortedArrayToBST(nums.subList(index + 1, nums.size()));
}
return treeNode;
}
}