Skip to content

Instantly share code, notes, and snippets.

@techsin
Created May 12, 2020 02:28
Show Gist options
  • Save techsin/38f86c5224f4c41fbcc83ad2c85b2978 to your computer and use it in GitHub Desktop.
Save techsin/38f86c5224f4c41fbcc83ad2c85b2978 to your computer and use it in GitHub Desktop.
/* Setup */
class Node {
left = null;
right = null;
constructor(val) {
this.val = val;
}
}
const A = new Node('A');
const B = new Node('B');
const C = new Node('C');
const D = new Node('D');
const E = new Node('E');
const F = new Node('F');
const G = new Node('G');
const H = new Node('H');
A.left = B;
A.right = C;
B.left = D;
B.right = E;
C.left = F;
C.right = G;
G.right = H;
// ==============
/* Tree */
// BFS:-
// iteratively
function bfsIter(node) {
const queue = [];
stack.push(node); //FIFO
while(stack.length) {
let curr = stack.shift();
console.log(curr.val);
if (curr.left) stack.push(curr.left);
if (curr.right) stack.push(curr.right);
}
}
// recursive
function bfsRec(node) {
bfs([node]);
function bfs(queue) {
if (!queue.length) return;
let curr = queue.shift();
console.log(curr.val);
if (curr.left) queue.push(curr.left);
if (curr.right) queue.push(curr.right);
bfs(queue);
}
}
// DFS:-
// recursive
// https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
// Preorder (Root, Left, Right) : 1 2 4 5 3
function dfsRecPre(node) {
if (!node) return;
console.log(node.val);
dfsRecPre(node.left);
dfsRecPre(node.right);
}
// Inorder (Left, Root, Right) : 4 2 5 1 3
function dfsRecIn(node) {
if (!node) return;
dfsRecIn(node.left);
console.log(node.val);
dfsRecIn(node.right);
}
// Postorder (Left, Right, Root) : 4 5 2 3 1
function dfsRecPost(node) {
if (!node) return;
dfsRecPost(node.left);
dfsRecPost(node.right);
console.log(node.val);
}
// iterative
function dfsItrPre() {
}
function dfsItrIn() {
}
function dfsItrPost() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment