📖
Coding interview questions
  • 👋Coding Interview
  • Easy
    • Two number sum
    • Validate Subsequence
    • Sorted Squared Array
    • Tournament Winner
    • Non-Constructible Change
    • Find Closest Value in BTS
    • Branch sum
    • Node Depths
    • Depth-first Search
    • Minimum Waiting Time
    • Class Photos
  • Medium
    • Three Number Sum
    • Smallest Difference
    • Move Element To End
    • Monotonic Array
    • Spiral Traverse
    • Longest Peak
    • Array Of Products
    • First Duplicate Value
    • Merge Overlapping Intervals
    • Zero Sum Subarray
    • BST Traversal
    • Validate BST
    • Min Height BST
    • Find Kth Largest Value In BST
    • Reconstruct BST
    • Invert Binary Tree
  • Hard
    • Three Number Sum
  • Really-Hard
    • Three Number Sum
Powered by GitBook
On this page
  1. Easy

Depth-first Search

Depth-first Search

You're given a Node class that has a name and an array of optional children nodes. When put together, nodes form an acyclic tree-like structure.

Implement the depthFirstSearch method on the Node class, which takes in an empty array, traverses the tree using the Depth-first Search approach (specifically navigating the tree from left to right), stores all of the nodes' names in the input array, and returns it.

If you're unfamiliar with Depth-first Search, we recommend watching the Conceptual Overview section of this question's video explanation before starting to code.

Sample Input

graph = A
     /  |  \
    B   C   D
   / \     / \
  E   F   G   H
     / \   \
    I   J   K

Sample Output

["A", "B", "E", "F", "I", "J", "C", "D", "G", "K", "H"]
class Node {
  constructor(name) {
    this.name = name;
    this.children = [];
  }

  addChild(name) {
    this.children.push(new Node(name));
    return this;
  }

  depthFirstSearch(array) {
    array.push(this.name);
    for (const child of this.children) {
      child.depthFirstSearch(array)
    }
    return array;
  }
}

// Do not edit the line below.
exports.Node = Node;
// O(n) time | O(h) space
function nodeDepths(root, depth = 0) {
  if(root === null) return 0
  return depth + nodeDepths(root.left, depth + 1) + nodeDepths(root.right, depth + 1);
}

// This is the class of the input binary tree.
class BinaryTree {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

// Do not edit the line below.
exports.nodeDepths = nodeDepths;
java

PreviousNode DepthsNextMinimum Waiting Time

Last updated 2 years ago

Page cover image