traverse a binary tree in javascript

Here's an example implementation of depth-first pre-order traversal of a binary tree in JavaScript:

index.tsx
function preOrderTraversal(node) {
  if (node !== null) {
    console.log(node.val); // visit the node
    preOrderTraversal(node.left); // traverse left subtree
    preOrderTraversal(node.right); // traverse right subtree
  }
}
229 chars
8 lines

Here's an example implementation of breadth-first traversal of a binary tree using a queue in JavaScript:

index.tsx
function breadthFirstTraversal(root) {
  if (root === null) {
    return;
  }
  
  const queue = [root];
  
  while (queue.length > 0) {
    const node = queue.shift();
    console.log(node.val); // visit the node
    
    if (node.left !== null) {
      queue.push(node.left); // enqueue left child
    }
    
    if (node.right !== null) {
      queue.push(node.right); // enqueue right child
    }
  }
}
407 chars
21 lines

gistlibby LogSnag