code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

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