Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

JavaScript binary tree


// calculate the average value for binary tree 
const AvgValue = (root) => {
  let result = [];
  let avg = 0;
  let sum = 0;
  let queue = [root];
  while (queue.length) {
    let current = queue.shift();
    result.push(current.data);
    if (current.left) queue.push(current.left);
    if (current.right) queue.push(current.right);
  }
  for (let i = 0; i < result.length; i++) {
    sum = sum + result[i];
  }
  avg = Math.floor(sum / result.length);
  return avg;
};
Source by gist.github.com #
 
PREVIOUS NEXT
Tagged: #JavaScript #binary #tree
ADD COMMENT
Topic
Name
2+2 =