DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Pre Order Traversal

var preOrderTraversal = function (root) {
  // preOrder Traversal ->
  //  1. Visit current node
  //  2. Recursively traverse through the left subtree
  //  3. Recursively traverse through the right subtree

  // Initialize array of values
  let result = [];

  // Recursive function to traverse through subtrees
  travel(root, result);

  return result;
};

const travel = (node, result) => {
  if (node === null) {
    return null;
  }
  result.push(node.val); // Visit node
  travel(node.left, result); // Traverse through left subtree
  travel(node.right, result); // Traverse through right subtree
};


Enter fullscreen mode Exit fullscreen mode

Top comments (0)