108. Convert Sorted Array to Binary Search Tree / 109. Convert Sorted List to Binary Search Tree
108. Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
My Solutions:
找到sorted array中点作为root,root.left是root左边的数,root.left 是root右边的数
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null) return null;
return helper(nums, 0, nums.length - 1);
}
private TreeNode helper(int[] nums, int start, int end) {
if (start > end) return null;
TreeNode node = new TreeNode(nums[(start + end) / 2]);
node.left = helper(nums, start, (start + end) / 2 - 1);
node.right = helper(nums, (start + end) / 2 + 1, end);
return node;
}
}
109. Convert Sorted List to Binary Search Tree
My Solutions:
和108类似,找到list的中点作为root。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
return helper(head, null);
}
public TreeNode helper(ListNode head, ListNode tail) {
if (head == tail) return null;
// 找到list中点
ListNode slow = head, fast = head;
while (fast != tail && fast.next != tail) {
fast = fast.next.next;
slow = slow.next;
}
TreeNode mid = new TreeNode(slow.val);
mid.left = helper(head, slow);
mid.right = helper(slow.next, tail);
return mid;
}
}
Last updated