DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.