Goal: To practice working with tree-like data structures (represented by objects) and recursive/iterative algorithms.
value property of the current node to the results array.children array, recursively call the same function.value property to the results array.children array) onto the stack. Important: To maintain the correct traversal order (left-to-right), you must push the children onto the stack in reverse order (right-to-left).null (an empty tree).This approach is the most intuitive for tree-like structures because the structure of a tree is itself recursive.
Code with Comments:
const depthFirstSearch = (tree) => {
// 1. Handle the edge case: if the tree is empty (null), return an empty array.
if (!tree) {
return [];
}
// 2. Create an array to store the traversal result.
const result = [];
// 3. Define a nested recursive function `traverse`.
// It will be called for each node (object) in the tree.
function traverse(node) {
// 4. Add the value of the current node to the result array.
// This is "visiting" the node.
result.push(node.value);
// 5. Iterate over all children of the current node.
// Ensure the node has children before iterating.
if (node.children) {
for (const child of node.children) {
// 6. For each child node, recursively call the `traverse` function.
// This is the "deepening" part of the search.
traverse(child);
}
}
}
// 7. Start the traversal by calling `traverse` on the root node of the tree.
traverse(tree);
// 8. Return the array with the traversal results.
return result;
};How It Works:
null. If so, traversal is impossible, and it returns an empty array.result is created to collect the node values.traverse function:
node, it immediately adds the node’s value (node.value) to the result array.children array of that node.traverse(child)). This is the key step in the recursion.traverse(tree) kicks off the recursive process from the root node.traverse(tree) finishes its execution, the result array will contain all node values in the correct order.This approach uses a “Stack” data structure to keep track of the nodes to visit. It avoids deep recursion, which can lead to a stack overflow on very large or unbalanced trees.
Code with Comments:
const depthFirstSearch = (tree) => {
// 1. Handle the edge case: if the tree is empty, return an empty array.
if (!tree) {
return [];
}
// 2. Create a array to store the result.
const result = [];
// 3. Create a stack and immediately push the root node (object) onto it.
const stack = [tree];
// 4. Start a loop that continues as long as there are nodes in the stack.
while (stack.length > 0) {
// 5. Pop the last node from the stack (LIFO - Last-In, First-Out).
const node = stack.pop();
// 6. "Visit" the node: add its value to the result array.
result.push(node.value);
// 7. Iterate over the children of the current node IN REVERSE ORDER.
// This is the key to the correct traversal order.
if (node.children) {
for (let i = node.children.length - 1; i >= 0; i--) {
// 8. Push each child node onto the stack.
stack.push(node.children[i]);
}
}
}
// 9. Return the array with the results.
return result;
};How It Works:
null and creates a result array. A stack is also created, and the root tree object is immediately pushed onto it.while Loop: The loop continues as long as the stack is not empty.stack.pop().node.value) is added to result.while loop finishes, all nodes have been processed, and the function returns the result.Write a function depthFirstSearch that takes the root node of a tree (represented as an object) and returns an array of all node values in the order of a Depth-First Search (DFS).
Depth-First Search is an algorithm for traversing or searching a tree data structure. The algorithm starts at the root node and explores as far as possible along each branch before backtracking.
Each node in the tree is an object with the following structure:
{
value: any, // The value of the node (any type)
children: Array<object> // An array of child nodes (objects of the same structure)
}For a tree represented by the object:
const tree = {
value: 'A',
children: [
{
value: 'B',
children: [
{ value: 'D', children: [] }
]
},
{
value: 'C',
children: [
{ value: 'E', children: [] },
{ value: 'F', children: [] }
]
}
]
};The result of calling depthFirstSearch(tree) should be: ['A', 'B', 'D', 'C', 'E', 'F'].
depthFirstSearch.tree), which is an object or null.tree is null, the function must return an empty array.Goal: To practice working with tree-like data structures (represented by objects) and recursive/iterative algorithms.
value property of the current node to the results array.children array, recursively call the same function.value property to the results array.children array) onto the stack. Important: To maintain the correct traversal order (left-to-right), you must push the children onto the stack in reverse order (right-to-left).null (an empty tree).This approach is the most intuitive for tree-like structures because the structure of a tree is itself recursive.
Code with Comments:
const depthFirstSearch = (tree) => {
// 1. Handle the edge case: if the tree is empty (null), return an empty array.
if (!tree) {
return [];
}
// 2. Create an array to store the traversal result.
const result = [];
// 3. Define a nested recursive function `traverse`.
// It will be called for each node (object) in the tree.
function traverse(node) {
// 4. Add the value of the current node to the result array.
// This is "visiting" the node.
result.push(node.value);
// 5. Iterate over all children of the current node.
// Ensure the node has children before iterating.
if (node.children) {
for (const child of node.children) {
// 6. For each child node, recursively call the `traverse` function.
// This is the "deepening" part of the search.
traverse(child);
}
}
}
// 7. Start the traversal by calling `traverse` on the root node of the tree.
traverse(tree);
// 8. Return the array with the traversal results.
return result;
};How It Works:
null. If so, traversal is impossible, and it returns an empty array.result is created to collect the node values.traverse function:
node, it immediately adds the node’s value (node.value) to the result array.children array of that node.traverse(child)). This is the key step in the recursion.traverse(tree) kicks off the recursive process from the root node.traverse(tree) finishes its execution, the result array will contain all node values in the correct order.This approach uses a “Stack” data structure to keep track of the nodes to visit. It avoids deep recursion, which can lead to a stack overflow on very large or unbalanced trees.
Code with Comments:
const depthFirstSearch = (tree) => {
// 1. Handle the edge case: if the tree is empty, return an empty array.
if (!tree) {
return [];
}
// 2. Create a array to store the result.
const result = [];
// 3. Create a stack and immediately push the root node (object) onto it.
const stack = [tree];
// 4. Start a loop that continues as long as there are nodes in the stack.
while (stack.length > 0) {
// 5. Pop the last node from the stack (LIFO - Last-In, First-Out).
const node = stack.pop();
// 6. "Visit" the node: add its value to the result array.
result.push(node.value);
// 7. Iterate over the children of the current node IN REVERSE ORDER.
// This is the key to the correct traversal order.
if (node.children) {
for (let i = node.children.length - 1; i >= 0; i--) {
// 8. Push each child node onto the stack.
stack.push(node.children[i]);
}
}
}
// 9. Return the array with the results.
return result;
};How It Works:
null and creates a result array. A stack is also created, and the root tree object is immediately pushed onto it.while Loop: The loop continues as long as the stack is not empty.stack.pop().node.value) is added to result.while loop finishes, all nodes have been processed, and the function returns the result.Write a function depthFirstSearch that takes the root node of a tree (represented as an object) and returns an array of all node values in the order of a Depth-First Search (DFS).
Depth-First Search is an algorithm for traversing or searching a tree data structure. The algorithm starts at the root node and explores as far as possible along each branch before backtracking.
Each node in the tree is an object with the following structure:
{
value: any, // The value of the node (any type)
children: Array<object> // An array of child nodes (objects of the same structure)
}For a tree represented by the object:
const tree = {
value: 'A',
children: [
{
value: 'B',
children: [
{ value: 'D', children: [] }
]
},
{
value: 'C',
children: [
{ value: 'E', children: [] },
{ value: 'F', children: [] }
]
}
]
};The result of calling depthFirstSearch(tree) should be: ['A', 'B', 'D', 'C', 'E', 'F'].
depthFirstSearch.tree), which is an object or null.tree is null, the function must return an empty array.The code editor is intentionally hidden on mobile.
Believe me, it's for the best: I am protecting you from the temptation to code in less-than-ideal conditions. A small screen and a virtual keyboard are not the best tools for a programmer.
📖 Now: Study the task, think through the solution. Act like a strategist.
💻 Later: Sit down at your computer, open the site, and implement all your ideas comfortably. Act like a code-jedi!