JSFiddle - React, Tailwind, and code Playground

by hescano

JavaScript

// return the sum of all values in the tree, including the root
function sumTheTreeValues(root){
  var result = 0;
  var tmp = [];
  while (tmp.length > 0 || root != null) {
  	if (root) {
    	tmp.push(root);
    	root = root.left;
    } else {
    	root = tmp.pop();
      result += root.value;
      root = root.right;
    }
  }
  
  return result;
}

var simpleNode = {value: 10, left: {value: 1, left: null, right: null}, right: {value: 2, left: null, right: null}};

console.log(sumTheTreeValues(simpleNode));