How to Calculate The Branch Sums of A Binary Tree

Christa Gammage
3 min readSep 27, 2020

So you’ve begun studying algorithms for you coding interview. Best of luck to you and your future endeavors! But first you must tackle the Binary Tree.

A Binary Tree is a structure that has one root node, which then branches into two left and right nodes. These are called children nodes. Those two left and right nodes may branch off into two more left and right nodes, and so on.

In order to calculate the sums of each branch, we must begin with the root node. At the root node, the sum is 0 because we have not begun adding any branches yet. Let’s break this down into a Javascript function. In your coding interview, you will most likely be given the following problem to solve:

Your function will only be able to take one argument: the root node. So we’re going to need to create a helper function that will be able to keep track of an array of the various sums, the current sum we are working with at each level of the Binary Tree, and what node we are on. First we will create our empty sums array, and then we will pass that, the runningSum (which will be initialized at 0), and the current node we are on into our helper function. At the end we want to return the array of sums of the branches, so we will be sure to write that into our code as well.

Now we begin to write our helper function, calculateBranchSums. Before we continue with our function, we want to check whether the node we are passing in exists at all. So let’s throw that in as a base case for our function.

If the node is not truthy, just return. Next, we want to calculate the runningSum. This is the new sum that reflects the value of the current node node and all nodes before it. After that, we will need to determine whether we are at the very bottom branch of the tree. In other words, we need to check that the current node does not have any children nodes. So we will say “If there is no left node and no right node on our current node” then….

If we are indeed at the bottom branch of our tree, then we want to add that newRunningSum to our sums array.

However, if we are not at the bottom of our tree, we want to recursively call this function to take care of the children nodes. So outside of our If statement, let’s pass in the node’s right child’s value, the new running sum, and our sums array into our function. We’ll also do the same for the node’s left child’s value.

By the end, our full function will look like this:

And that is how you calculate the sums of the branches of a Binary Tree in Javascript!

--

--