Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
很简单的二分法,只要给出Array的开始和结束下标作为参数传入即可。
public TreeNode sortedArrayToBST(int[] num) {
return constructBST(num,0,num.length-1);
}
public TreeNode constructBST(int[] num, int start, int end) {
if(start>end)
return null;
if(start==end)
return new TreeNode(num[start]);
int mid = (start+end)/2;
TreeNode root = new TreeNode(num[mid]);
root.left = constructBST(num, start, mid-1);
root.right = constructBST(num, mid+1, end);
return root;
}
Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
对于链表来说,情况稍微复杂一些,最简单的思路是可以遍历一遍链表存到array中然后构建。这里采用直接构建的方法,就是用快慢指针找到链表中点,左半部分链表终点指向null,递归构建成左子树。右半部分递归构建成右子树即可。如果不想破坏原有链表那么可以采用先存到array中再构建的方法。
public TreeNode sortedListToBST(ListNode head) {
if(head==null)
return null;
if(head.next == null)
return new TreeNode(head.val);
ListNode fast = head.next;
ListNode slow = head;
while(fast!=null && fast.next!=null && fast.next.next!=null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode root = slow.next;
slow.next = null;
TreeNode tRoot = new TreeNode(root.val);
tRoot.left = sortedListToBST(head);
tRoot.right = sortedListToBST(root.next);
return tRoot;
}