class Node {
constructor(data) {
this.left = null;
this.right = null;
this.data = data;
}
}
// depth first search tree traversal using recursive
//static implementation
const depthFirstTraversal = (root) => {
if (root === null) return [];
const leftValues = depthFirstTraversal(root.left); //[2 , 4 , 5 ]
const rightValues = depthFirstTraversal(root.right); // [3 , 6 , 7 ]
return [root.data, ...leftValues, ...rightValues];
};
const one = new Node(1);
const two = new Node(2);
const three = new Node(3);
const four = new Node(4);
const five = new Node(5);
const six = new Node(6);
const seven = new Node(7);
one.left = two;
one.right = three;
two.left = four;
two.right = five;
three.left = six;
three.right = seven;
// console.log(depthFirstTraversal(one)); // [1 ,2 , 4 , 5 ,3 , 6 ,7]
// depth first search tree traversal using while loop :
const depthFirstTraversal2 = (root) => {
if (root === null) return [];
const result = [];
const stack = [root];
while (stack.length > 0) {
const current = stack.pop();
result.push(current.data);
if (current.right) stack.push(current.right);
if (current.left) stack.push(current.left);
}
return result;
};
console.log(depthFirstTraversal2(one)); // [1 ,2 , 4 , 5 ,3 , 6 ,7]