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

589 Preorder Traversal

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

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

const preorderTraversal = root => {
  let result = []
  if (!root) {
    return result
  }
  const innerPreorderTraversal = root => {
    if (root == null) {
      return
    }
    result.push(root.val)
    if (root.children) {
      for (let i = 0; i < root.children.length; i++) {
        innerPreorderTraversal(root.children[i])
      }
    }
  }
  innerPreorderTraversal(root)
  return result
}

test('preorderTraversal', () => {
  const t1 = new TreeNode(1)
  t1.children = [new TreeNode(3, [new TreeNode(5), new TreeNode(6)]), new TreeNode(2), new TreeNode(4)]
  expect(preorderTraversal(t1)).toEqual([1, 3, 5, 6, 2, 4])
})

Created 2020-12-06T15:26:30+05:18, updated 2020-12-06T15:36:55+05:18 · History · Edit