Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update ch4-q02.js #10

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 58 additions & 19 deletions src/chapter4/ch4-q02.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,45 @@
'use strict';

import { Tree } from './helpers';
// import { Tree } from './helpers';


// * The prior solution can be improved upon and run in
// Time: O(N);
// Space: O(N);
/* A function that constructs Balanced Binary Search Tree
from a sorted array */

export function main(arr) {
if (!arr || arr.length < 1) return null;

const tree = new BinaryTree();
//if its only one number its a node not a tree else create tree;
return arr.length === 1 ? new Node(arr[0]) :
tree.createBst(arr, 0, arr.length - 1);
}

class Node {
constructor(data) {
this.val = data;
this.left = this.right = null;
}
}

class BinaryTree {

createBst(arr, start, end) {
if (start > end) return null;
const mid = Math.floor((start + end) / 2),
node = new Node(arr[mid]);


node.left = this.createBst(arr, start, mid - 1);
node.right = this.createBst(arr, mid + 1, end);
return node;
}
}



/**
* As the list is already sorted the best way to create a balanced tree is by
Expand All @@ -12,22 +51,22 @@ import { Tree } from './helpers';
* Time: O(N lg N)
* Additional space: O(N)
*/
export function makeBalancedTree(values) {
let tree = new Tree();
if (values && values.length) {
add(tree, values, 0, values.length - 1);
}
return tree;
}
// export function makeBalancedTree(values) {
// let tree = new Tree();
// if (values && values.length) {
// add(tree, values, 0, values.length - 1);
// }
// return tree;
// }

function add(tree, values, start, end) {
if (start === end) {
tree.add(values[start]);
}
else if (start < end) {
let mid = start + Math.floor((end - start) / 2);
tree.add(values[mid]);
add(tree, values, start, mid - 1);
add(tree, values, mid + 1, end);
}
}
// function add(tree, values, start, end) {
// if (start === end) {
// tree.add(values[start]);
// }
// else if (start < end) {
// let mid = start + Math.floor((end - start) / 2);
// tree.add(values[mid]);
// add(tree, values, start, mid - 1);
// add(tree, values, mid + 1, end);
// }
// }