JSFiddle - React, Tailwind, and code Playground

by gbsandeep

JavaScript

var count = function(tree) {
    // Stack is by default empty
    var stack = [];

    var count = 0;

    // Initially set node to the tree root. 'node' always points to the item being processed. 
    //Each node can have left and right children. 
    //They can be null as well.
    // Comparison is to check if the 'node' is undefined or null 
    // count is incremented if there a left or right children is found. 
    // stack.pop() removes the top most element from the array/stack. 

    for (var node = tree; node; count++, node = stack.pop()) {

      // verify if left child exists, then push. This will add to the count when it is popped.  

      if (node.left) stack.push(node.left);

      // verify if right child exists, then push. This will add to the count when it is popped.

  if (node.right) stack.push(node.right);
    }
    return count;
};

var tree = {left: {left: {}}, right: {}};

console.log(count(tree));