RObservations #21: Solving “Tree Sum” Problems with Recursion and Iterative Approaches

[This article was first published on r – bensstats, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.


In my previous blogs, I introduced how to preform depth-first and breadth-first searches in R with R6 objects. After knowing how to do this I explored solving tree-includes problems with both of these searches. In this blog I am going to share how to solve binary “tree sum” problems using recursive and iterative approaches. As was the case with previous blogs, this blog was written based on Alvin the Programmer’s video on binary tree algorithms for technical interviews, but specified for the R user.

The Problem

The problem of finding a binary tree sum relates to finding the sum of all the nodes in a given tree. For the tree:

         / \
        11  4
       /  \  \
      4    2  1

It is possible to find the sum (25) using with either recursive or iterative approaches.

To set up the above tree we will use R6 classes. If you have read the previous blogs, the objects are the same but are specified for this problem.

The R code for doing this is:

node <- R6Class("Node",
                  initialize= function(val=NULL,
                    self$val<- val
                    self$left<- left

b <- node$new(val=11)
d <- node$new(val=4)
f <- node$new(val=1)

a$left<- b

Using Recursion.

In my last blog, I shared how I was unable to write a depth-first solution in R with recursion. However this time, I was able to figure it out thanks to this answer on StackOverflow. Apparently, for recursion R will not allow for “vector notation” to be implemented, as such list notation should be used. In other words, for recursion, avoid using $ to index variables as your code will result in an error. Instead use [[]].

The recursive tree-sum code is:

treeSum <- function(root){

  # Dealing with null values

  # The magic of recursion
  return(root[['val']] + treeSum(root[['left']])+ treeSum(root[['right']]))



## [1] 25

Using an iterative approach

To solve this problem iteratively, all that needs to be done is to modify the breadth first code to calculate a rolling sum as the binary tree is traversed. While it is possible to also have an iterative depth first search, because it was already done recursively, breadth first is implemented for this iterative approach.

treeSum <- function(root){
  totalSum <- 0
  while (length(queue)> 0){

    totalSum <- totalSum + current$val
      queue<- append(queue,current$left)
      queue<- append(queue,current$right)
    # remove first element



## [1] 25


There you have it! Another binary tree problem in the books! I’m pretty happy I got to figure out how recursion works and how to implement it in R. It definitely makes for cleaner looking code. I hope to be able to use it for future projects and make cleaner R code with it and R6 objects!

Want to see more of my content?

Be sure to subscribe and never miss an update!

To leave a comment for the author, please follow the link and comment on their blog: r – bensstats. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)