R: updating a variable defined in a function using a helper function without a return value

44 Views Asked by At

Reproducible code

# recursive helper function
# a = array representation of the binary tree
# i = position of the root that we are trying to add to inorder_a
# inorder_a = array representation of a up till i
add_node <- function(a, i, inorder_a) {
  print(paste("a:", paste(a, collapse = ' '), 
              "i:", i, 
              'a[i]:', a[i],
              "inorder_a:", paste(inorder_a, collapse = ' '), 
              sep = ' '))
  if(is.na(a[i]) == FALSE) {
    # add the left child of the root node in position i, which is in position 2*i
    add_node(a, 2*i, inorder_a)
    # add the root node in position i of a
    inorder_a <- append(inorder_a, a[i])
    # add the right child of the root node in position i, which is in position (2*i + 1)
    add_node(a, (2*i)+1, inorder_a)
  }
}

# main function that calls add_node() to return the in-order traversal of binary tree array a
get_inorder_traversal_recursion <- function(a) {
  n <- length(a)
  
  # corner cases
  if(n <= 1) return(a)
  
  # initiate output array
  inorder_a <- c()
  
  # add binary tree a, whose head/root is in position 1
  add_node(a, 1, inorder_a)
  
  return(inorder_a)
}


When I call get_inorder_traversal_recursion(c(1, NA, 2, 3)), I get the following print out from the print function that I set up to see what's going on iteratively. The print out is as expected where inorder_a is being updated iteratively.

[1] "a: 1 NA 2 3 i: 1 a[i]: 1 inorder_a: "
[1] "a: 1 NA 2 3 i: 2 a[i]: NA inorder_a: "
[1] "a: 1 NA 2 3 i: 3 a[i]: 2 inorder_a: 1"
[1] "a: 1 NA 2 3 i: 6 a[i]: NA inorder_a: 1"
[1] "a: 1 NA 2 3 i: 7 a[i]: NA inorder_a: 1 2"

However, the return value of get_inorder_traversal_recursion(c(1, NA, 2, 3)) is NA because inorder_a within get_inorder_traversal_recursion(c(1, NA, 2, 3)) never got updated, which is what I had expected would happen with the call to add_node(a, 1, inorder_a) within get_inorder_traversal_recursion.

Can someone explain why inorder_a was never updated within get_inorder_traversal_recursion(c(1, NA, 2, 3)) when the helper function add_node() was called up update it?

The reason why I don't have a return value to add_node() is because I'm not sure where to put it...

0

There are 0 best solutions below