1

Write a function that returns the sum of all nodes, including root

var nodes = {
  value: 7,
  left: { value: 1, left: null, right: null },
  right: { value: 4, left: null, right: null }
};

Considering this, result should be equal to 12.

sumTheTreeValues = root => {
  console.log(root.value);
  if (root.left != null) {
    sumTheTreeValues(root.left);
  }
  if (root.right != null) {
    sumTheTreeValues(root.right);
  }
};

If this code will log

7
1
4

How to return the sum of these numbers without having to pass new parameter ?

1
  • Start by trying to return a value instead of logging it... Commented Mar 31, 2018 at 20:47

2 Answers 2

2

Add the left and right nodes value to the current value and return:

var nodes = {
  value: 7,
  left: { value: 1, left: null, right: null },
  right: { value: 4, left: null, right: null }
};

sumTheTreeValues = root => {
  let value = root.value;

  if (root.left != null) {
    value += sumTheTreeValues(root.left);
  }
  if (root.right != null) {
    value += sumTheTreeValues(root.right);
  }
  
  return value;
};

console.log(sumTheTreeValues(nodes));

You can also shorten it up a bit because null is automatically casted to 0 when added to a number:

var nodes = {
  value: 7,
  left: { value: 1, left: null, right: null },
  right: { value: 4, left: null, right: null }
};

sumTheTreeValues = root => root.value + 
  (root.left && sumTheTreeValues(root.left)) + 
  (root.right && sumTheTreeValues(root.right));

console.log(sumTheTreeValues(nodes));

Sign up to request clarification or add additional context in comments.

Comments

-1

Another way is to wrap your function inside another:

 function sum(root) {
    var result = 0;
    var sumTheTreeValues = root => {
       result += root.value
       if (root.left != null) {
          sumTheTreeValues(root.left);
        }
        if (root.right != null) {
           sumTheTreeValues(root.right);
        }
     };
     sumTheValues(root)
     return result;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.