Balanced BST at max one node
by raviteja gunda
CSS
//[8, 10, 12, 15, 16, 20, 25] - wrong
EO [15,
10, 20,
8, 12, 16, 25]
// [1, 3, 5, 7, 9] right
[5,
1, 7,
null, 3, null, 9]
// [-4, -2, 0, 2, 4, 6] wrong
[0,
-4, 4,
null, -2, 2, 6]
//: [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]
[-1,
-4, 3,
-5, -3, 1, 4,
null, null, null, -2, null, 2, null, 5]
JavaScript
/*
For your reference:
const BinaryTreeNode = class {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
};
*/
/**
* @param {list_int32} a
* @return {BinaryTreeNode_int32}
*/
function build_balanced_bst(a) {
// Write your code here.
if(a.length == 0){
return null;
}
let rootValue = Math.floor((a.length)/2);
//buildBst(a[root], root);
let root = new BinaryTreeNode(a[rootValue],null,null);
console.log(root);
for(let i=0; i<rootValue; i++){
console.log('for', a[i]);
buildBst(a[i],root);
}
for(let i=rootValue+1; i<a.length; i++){
console.log('for second', a[i]);
buildBst(a[i],root);
}
console.log(root);
return root;
}
function buildBst(value, root, prev) {
console.log(root);
console.log('value', value);
console.log(root.value);
if(root.value < value) {
if(root.right == null) {
root.right = new BinaryTreeNode(value,null,null);
} else {
return buildBst(value, root.right, root);
}
} else if (root.value > value) {
if(root.left == null) {
root.left = new BinaryTreeNode(value,null,null);
} else {
return buildBst(value, root.left, root);
}
}
}