Created
May 8, 2022 18:02
-
-
Save gtaing1/a225974f02cabc8f7910121687dbc599 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Problem | |
Convert a sorted array into a balanced BST. Return the root of the created tree. | |
Function Signature: | |
func arrayToBST(input: [Int]) -> Node | |
Target runtime and space complexity: | |
Runtime: O(n) | |
Space: O(1), not including space used to create BST, otherwise O(n) | |
Examples: | |
[1, 2, 3, 4, 5] => | |
[1, 2, 3, 4] | |
class TreeNode { | |
constructor(value, left = null, right = null) { | |
this.value = value; | |
this.left = left; | |
this.right = right; | |
} | |
} | |
function printTree(root) | |
{ | |
let left = 0; | |
let right = root.length-1; | |
let newTree = arrayToBST(root, left, right); | |
return newTree; | |
} | |
function arrayToBST(root, left, right) { | |
if(!root) return null; | |
if (left > right) | |
{ | |
return null; | |
} | |
let midPoint = Math.ceil(left+(right-left)/2); | |
// let midPoint = Math.round(left+(right-left)/2); | |
console.log(midPoint); | |
let newNode = new TreeNode(root[midPoint]); | |
newNode.left = arrayToBST(root, left, midPoint-1); | |
newNode.right = arrayToBST(root, midPoint+1, right); | |
return newNode; | |
} | |
const tree1 =[1, 2, 3, 4, 5]; | |
/*/ | |
3 | |
1 4 | |
2 5 | |
3 | |
/ \ | |
2 4 | |
/ \ | |
1 5 | |
\ | |
6 | |
*/ | |
const tree2 =[1, 2, 3]; | |
const tree3 =[1, 2]; | |
const tree4 =[1, 2, 3, 4, 5, 6]; | |
console.log(printTree(tree4)) | |
// console.log(printTree(tree2)) /* | |
// 2 | |
// 1 3 */ | |
// // // console.log(printTree(tree3)) /* | |
/* 4 | |
2. 6 | |
1 3. 5 | |
// 1 | |
// 2 | |
// */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment