How to iterate through a binary tree using JavaScript?

Let's assume that we are working with the following binary tree:

terminal
             1                     
            / \
           /   \ 
          2     3                  
         /     / 
        /     /   
       4      5                    
      /      / \ 
     /      /   \
    6      7     8                 
     \          / \
      \        /   \
       9      10   11              

If we want to print the nodes in-order traversal, we expect:

6 -> 9 -> 4 -> 2 -> 1 -> 7 -> 5 -> 10 -> 8 -> 11 -> 3

Let's define a node:

jsx
const node = (value, left, right) => ({value: value, left: left, right: right});

Let's define the tree:

jsx
// We create the nodes from left to right and from top to bottom
// We assign -1 if the node has no children
const tree = [node(1, 2, 3), node(2, 4, -1), ... , node(11, -1, -1)];

How to iterate through the whole tree:

jsx
const inOrderTraversal = (node, tree) => {
    
    let nextLeftNode  = tree[node - 1].left;
    let nextRightNode = tree[node - 1].right;
    
    // Look for left children
    if(nextLeftNode !== -1) 
        inOrderTraversal(nextLeftNode, tree);
    
    // Print current node
    console.log(node);
    
    // Look for right children
    if(nextRightNode !== -1)
        inOrderTraversal(nextRightNode, tree);
    
}

inOrderTraversal(1, tree);

// 6, 9, 4, 2, 1, 7, 5, 10, 8, 11, 3

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.