preorder traversal of a binary tree in javascript

index.tsx
class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}

function preorder(node) {
  if (node === null) {
    return;
  }
  console.log(node.data); // process the node
  preorder(node.left); // traverse the left subtree
  preorder(node.right); // traverse the right subtree
}

const root = new Node("A");
root.left = new Node("B");
root.right = new Node("C");
root.left.left = new Node("D");
root.left.right = new Node("E");
root.right.left = new Node("F");
root.right.right = new Node("G");

// example usage
preorder(root); // A, B, D, E, C, F, G
601 chars
28 lines

This code defines a Node class to represent individual nodes in a binary tree, and a recursive preorder function to traverse the nodes in preorder fashion. The preorder function takes a node argument as input, and recursively processes the node, its left subtree, and its right subtree in that order.

Finally, an example binary tree is defined and the preorder function is called with the root node to traverse the tree in preorder fashion. The expected output of the program for this example is A, B, D, E, C, F, G.

gistlibby LogSnag