Skip to content

Instantly share code, notes, and snippets.

@andreabradpitto
Last active October 19, 2022 17:06
Show Gist options
  • Save andreabradpitto/5383d118958cda9a38e60e53d0dd59b0 to your computer and use it in GitHub Desktop.
Save andreabradpitto/5383d118958cda9a38e60e53d0dd59b0 to your computer and use it in GitHub Desktop.
Exercises with binary trees in Javascript
class TreeNode {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
/*
"A class may have only a single constructor"
constructor(value, left, right){
this.value = value;
this.left = left;
this.right = right;
}
*/
}
function depth_first_iterative_alg(root){
if (root == null) return [];
const stack = [root];
const result = [];
while (stack.length > 0){
const curr_node = stack.pop();
//console.log(curr_node.value);
result.push(curr_node); // If I push curr_node.value, I will instead return the array of values instead of TreeNode
if (curr_node.right) stack.push(curr_node.right); // The "if (curr_node.right)" condition is equivalent
if (curr_node.left) stack.push(curr_node.left); // to "if (curr_node.right != null)"
}
return result;
}
function depth_first_recursive_alg(root){
if (root == null) return [];
const left_values = depth_first_recursive_alg(root.left);
const right_values = depth_first_recursive_alg(root.right);
return [root].concat(left_values, right_values);
//The return could also be carried out via the Spread operator:
//return [root, ...left_values, ...right_values];
}
// Breadth-first algorithm is easily implementable only in an iterative form
function breadth_first_alg(root){
if (root == null) return [];
const queue = [root];
const result = [];
while (queue.length > 0){
const curr_node = queue.shift();
//console.log(curr_node.value);
result.push(curr_node);
if (curr_node.left != null) queue.push(curr_node.left);
if (curr_node.right != null) queue.push(curr_node.right);
}
return result;
}
// binary tree test example:
//
// a
// / \
// b c
// / \ \
// d e f
//
const a = new TreeNode("a");
const b = new TreeNode("b");
const c = new TreeNode("c");
const d = new TreeNode("d");
const e = new TreeNode("e");
const f = new TreeNode("f");
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
console.log("Depth first iterative solution:")
alg1_output = depth_first_iterative_alg(a);
alg1_output.forEach(function(elem){
console.log(elem.value);
});
console.log("\nDepth first recursive solution:")
alg2_output = depth_first_recursive_alg(a);
alg2_output.forEach(function(elem){
console.log(elem.value);
});
console.log("\nBreadth first iterative solution:")
alg3_output = breadth_first_alg(a);
alg3_output.forEach(function(elem){
console.log(elem.value);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment