Skip to content

Instantly share code, notes, and snippets.

@BilalAlam173
Created October 21, 2020 22:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BilalAlam173/fef7dc20591a9a65cc9fe6c69cbdfad4 to your computer and use it in GitHub Desktop.
Save BilalAlam173/fef7dc20591a9a65cc9fe6c69cbdfad4 to your computer and use it in GitHub Desktop.
Different types of Binary Tree Traversals implementation in javascript
function Node(key, left, right) {
this.key = key;
this.right = right;
this.left = left;
}
function BinaryTree(root) {
this.root = root;
}
BinaryTree.prototype.breadthFirst = {
levelOrder: function (cursor) {
const queue = [cursor];
while (queue.length > 0) {
cursor = queue.shift();
process.stdout.write(cursor.key + " ");
if (cursor.left) {
queue.push(cursor.left);
}
if (cursor.right) {
queue.push(cursor.right);
}
}
}
}
BinaryTree.prototype.depthFirst = {
inOrder: function (cursor) {
if (!cursor) return;
this.inOrder(cursor.left);
process.stdout.write(cursor.key + " ");
this.inOrder(cursor.right);
},
preOrder: function (cursor) {
if (!cursor) return;
process.stdout.write(cursor.key + " ");
this.preOrder(cursor.left);
this.preOrder(cursor.right);
},
postOrder: function (cursor) {
if (!cursor) return;
this.postOrder(cursor.left);
this.postOrder(cursor.right);
process.stdout.write(cursor.key + " ");
}
}
let n4 = new Node('4');
let n2 = new Node('2', n4);
let n5 = new Node('5');
let n6 = new Node('6');
let n3 = new Node('3', n5, n6);
let n1 = new Node('1', n2, n3);
let b1 = new BinaryTree(n1);
console.log('----------Depth First-----------')
console.log('\n*In-order Traversal*')
b1.depthFirst.inOrder(b1.root);
console.log('\n\n*Pre-order Traversal*')
b1.depthFirst.preOrder(b1.root);
console.log('\n\n*Post-order Traversal*')
b1.depthFirst.postOrder(b1.root);
console.log('\n\n\n----------Breadth First----------')
console.log('\n*Level-order Traversal*')
b1.breadthFirst.levelOrder(b1.root);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment