Convert Sorted Array & List to Binary Search Tree
Given an array(list) where elements are sorted in ascending order, convert it to a height balanced BST.
思路很简单,因为是sorted,所以balanced BST的root一定在中间元素上。然后root的左子树相当于是由左半部分元素组成的一颗平衡BST,右子树相当于是由右半部分元素组成的一棵平衡BST。
实现起来array比较简单,找中点下标,递归即可。
list找中点需要用到fast, slow指针。fast每次走两步,slow每次走一步。fast走到底,slow刚好到达中间值。同时为了递归,找到中间元素后,记得把中间元素前一个元素的next设置为null。为此,我们需要用一个记录slow前一个元素的指针pre。
Array:
public TreeNode sortedArrayToBST(int[] num) {
return helper(num, 0, num.length - 1);
}
private TreeNode helper(int[] num, int low, int high) {
if (low > high) {
return null;
}
int mid = (low + high) / 2;
TreeNode node = new TreeNode(num[mid]);
node.left = helper(num, low, mid - 1);
node.right = helper(num, mid + 1, high);
return node;
}
List:
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
ListNode helper = new ListNode(0);
helper.next = head;
ListNode pre = helper;
while (fast != null && fast.next != null) {
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
TreeNode node = new TreeNode(slow.val);
pre.next = null;
node.left = sortedListToBST(helper.next);
node.right = sortedListToBST(slow.next);
return node;
}