基础知识
-
二叉树搜索树BST的中序遍历是升序序列,所以108和109中给出的数组和链表的顺序即为BST中序遍历的顺序
-
给定BST的中序序列,肯定没法唯一确定BST的
-
在2的基础上要求BST平衡,也是没法唯一确定BST的
leetcode 108
public TreeNode sortedArrayToBST(int[] nums) {
return helper(nums, 0, nums.length - 1);
}
public TreeNode helper(int[] nums, int left, int right){
if (left > right){
return null;
}
int mid = (left + right) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums, left, mid - 1);
root.right = helper(nums, mid + 1, right);
return root;
}
时间复杂度:O(N),数组中每个元素都要访问一次
空间复杂度:O(LOGN),二分法的递归栈
leetcode 109
直接用链表做
public TreeNode sortedListToBST(ListNode head) {
if (head == null){
return null;
}
ListNode fast = head;
ListNode slow = head;
ListNode pre = head;
while (fast != null && fast.next != null){
pre = slow;
fast = fast.next.next;
slow = slow.next;
}
ListNode mid = slow;
ListNode rightPart = mid.next;
pre.next = null;
TreeNode root = new TreeNode(mid.val);
if (head == mid){
return root;
}
root.left = sortedListToBST(head);
root.right = sortedListToBST(rightPart);
return root;
}
时间复杂度:O(Nlogn)
空间复杂度:O(logN)
也可以先转换成数组,然后用108的解法做,相当于用空间换时间。