public TreeNode sortedListToBST(ListNode head) {
if(head==null) return new TreeNode(0);
ArrayList<TreeNode> arr=new ArrayList<TreeNode>();
while(head!=null)
{
arr.add(new TreeNode(head.val));
head=head.next;
} return BST(arr,0,arr.size()-1);
}
TreeNode BST(ArrayList<TreeNode> list,int start,int end)
{
if(start>=end)
{
return list.get(start);
}
else
{
int mid=start+(end-start)/2;
TreeNode root=list.get(mid);
root.left=BST(list,start,mid-1);
root.right=BST(list,mid+1,end); return root;
}
}
相关文章
- Leetcode: Convert sorted list to binary search tree (No. 109)
- leetcode 108 Convert Sorted Array to Binary Search Tree ----- java
- 【LeetCode】108. Convert Sorted Array to Binary Search Tree 解题报告 (Java & Python)
- [Leetcode][JAVA] Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted Array to Binary Search Tree 解题报告
- Convert Sorted Array to Balanced Binary Search Tree (BST)
- 【LeetCode-面试算法经典-Java实现】【109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)】
- Convert Sorted Array to Binary Search Tree
- Convert Sorted Array to Binary Search Tree - LeetCode
- Java [Leetcode 235]Lowest Common Ancestor of a Binary Search Tree