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:
1 2 3 4 5 6 7 8 9
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:
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {number[]} nums * @return {TreeNode} */ var sortedArrayToBST = function(nums) { return dfs(0, nums.length - 1);
functiondfs(start, end) { if (start > end) returnnull;
var mid = (start + end) >> 1; var node = new TreeNode(nums[mid]); node.left = dfs(start, mid - 1); node.right = dfs(mid + 1, end);
return node; } };
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.
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:
1 2 3 4 5 6 7 8 9
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
/** * Definition for singly-linked list with a random pointer. * function RandomListNode(label) { * this.label = label; * this.next = this.random = null; * } */
/** * @param {RandomListNode} head * @return {RandomListNode} */ var copyRandomList = function(head) { if (!head) returnnull;
let hash = newMap(); let newArr = []; let node = head;