LeetCode——convert-sorted-list-to-binary-search-tree && convert-sorted-array-to-binary-search-tree
Q:给定一个单链表,其中的元素按升序排序,请将它转化成平衡二叉搜索树(BST)
A:
public static TreeNode sortedListToBST(ListNode head) {
if (head == null)
return null;
return toBST(head, null);
}
private static TreeNode toBST(ListNode head, ListNode tail) {
if (head == tail)
return null;
// 申请两个指针,fast移动速度是low的两倍
ListNode fast = head;
ListNode slow = head;
while (fast != tail && fast.next != tail) {
fast = fast.next.next;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = toBST(head, slow);
root.right = toBST(slow.next, tail);
return root;
}
Q:给出一个升序排序的数组,将其转化为平衡二叉搜索树(BST).
A:
public TreeNode sortedArrayToBST(int[] nums) {
if(nums==null||nums.length==0)
return null;
return sortedArrayToBST(nums,0,nums.length-1);
}
private TreeNode sortedArrayToBST(int[] nums, int left, int right) {
if(right<left)
return null;
if(left==right)
return new TreeNode(nums[left]);
int mid=left+(right-left+1)/2;
TreeNode root=new TreeNode(nums[mid]);
root.left=sortedArrayToBST(nums,left,mid-1);
root.right=sortedArrayToBST(nums,mid+1,right);
return root;
}