code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

03 Depth First Search

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

function TreeNode(val, children) {
  this.val = val
  this.children = children || []
}

const depthFirstSearch = root => {
  let found = false
  const traverse = root => {
    if (root == null) {
      return
    }
    console.log(root.val)
    if (root.children) {
      for (let i = 0; i < root.children.length; i++) {
        traverse(root.children[i])
      }
    }
  }
  traverse(root)
  return found
}

const t1 = new TreeNode('A')
t1.children = [
  new TreeNode('B', [new TreeNode('E'), new TreeNode('F', [new TreeNode('I'), new TreeNode('J')])]),
  new TreeNode('C'),
  new TreeNode('D', [new TreeNode('G', [new TreeNode('K')]), new TreeNode('H')]),
]
console.log(depthFirstSearch(t1))

Created 2020-12-18T07:19:18+05:18 · Edit