Construst Tree
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) return null;
return helper(nums, 0, nums.length - 1);
}
private TreeNode helper(int[] nums, int left, int right) {
if (left == right) return new TreeNode(nums[left]);
if (left > right) return null;
int mid = (right + left) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums, left, mid - 1);
root.right = helper(nums, mid + 1, right);
return root;
} def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums or len(nums) == 0:
return None
return self.helper(nums, 0, len(nums) - 1)
def helper(self, nums, L , R):
if L > R:
return None
if L == R:
return TreeNode(nums[L])
mid = L + (R - L) // 2
curt = TreeNode(nums[mid])
curt.left = self.helper(nums, L, mid - 1)
curt.right = self.helper(nums, mid + 1, R)
return curtUse fast and slow pointer to find mid of the list. Construct root as the mid value. Recursively construct root left as value in range Integer.MIN_VALUE and mid.val, root right as value in range mid.val and Integer.MAX_VALUE. Return null if exceed the range.
public TreeNode sortedListToBST(ListNode head) {
return buildTree(head, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private TreeNode buildTree(ListNode head, int min, int max) {
ListNode mid = getMid(head);
if (mid == null || mid.val <= min || mid.val >= max) return null;
TreeNode root = new TreeNode(mid.val);
root.left = buildTree(head, min, root.val);
root.right = buildTree(mid.next, root.val, max);
return root;
}
private ListNode getMid(ListNode head) {
ListNode pre = new ListNode(-1);
pre.next = head;
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
pre = slow;
fast = fast.next.next;
slow = slow.next;
}
pre.next = null;
return slow;
}Use a StringBuilder to append elements from tree to string.
Use BST characteristics to construct BST.
Construct tree key and count the number of subtrees in the same pattern.
Break a big problem into several small problems. Get all possible combinations under N = 2 then construct the tree according to the combinations. Use memo.
Use a pointer in preorder array to track the next number, also use a L and R boundary in inorder array to define the range. Make a hashmap to store the elements and its corresponding indicies.
Get the index in inorder array, the left node is in inorder range between inL and index - 1, right node is between index + 1 and inR. In preorder, the next left node is i + 1, right is i + size of left range + 1, which is i + inIndex - inLeft + 1
Similar as the question above. Postorder runs opposite as preorder.
Maintain two ranges.
Last updated
Was this helpful?