Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8737103
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T10:26:23+00:00 2026-06-13T10:26:23+00:00

I am attempting to return a list of widgets from an N-tree data structure.

  • 0

I am attempting to return a list of widgets from an N-tree data structure. In my unit test, if i have roughly about 2000 widgets each with a single dependency, i’ll encounter a stack overflow. What I think is happening is the for loop is causing my tree traversal to not be tail recursive. what’s a better way of writing this in scala? Here’s my function:

protected def getWidgetTree(key: String) : ListBuffer[Widget] = {
  def traverseTree(accumulator: ListBuffer[Widget], current: Widget) : ListBuffer[Widget] = {
    accumulator.append(current)

    if (!current.hasDependencies) {
      accumulator
    }  else {
      for (dependencyKey <- current.dependencies) {
        if (accumulator.findIndexOf(_.name == dependencyKey) == -1) {
          traverseTree(accumulator, getWidget(dependencyKey))
        }
      }

      accumulator
    }
  }

  traverseTree(ListBuffer[Widget](), getWidget(key))
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T10:26:24+00:00Added an answer on June 13, 2026 at 10:26 am

    The reason it’s not tail-recursive is that you are making multiple recursive calls inside your function. To be tail-recursive, a recursive call can only be the last expression in the function body. After all, the whole point is that it works like a while-loop (and, thus, can be transformed into a loop). A loop can’t call itself multiple times within a single iteration.

    To do a tree traversal like this, you can use a queue to carry forward the nodes that need to be visited.

    Assume we have this tree:

    //        1
    //       / \  
    //      2   5
    //     / \
    //    3   4
    

    Represented with this simple data structure:

    case class Widget(name: String, dependencies: List[String]) {
      def hasDependencies = dependencies.nonEmpty
    }
    

    And we have this map pointing to each node:

    val getWidget = List(
      Widget("1", List("2", "5")),
      Widget("2", List("3", "4")),
      Widget("3", List()),
      Widget("4", List()),
      Widget("5", List()))
      .map { w => w.name -> w }.toMap
    

    Now we can rewrite your method to be tail-recursive:

    def getWidgetTree(key: String): List[Widget] = {
      @tailrec
      def traverseTree(queue: List[String], accumulator: List[Widget]): List[Widget] = {
        queue match {
          case currentKey :: queueTail =>        // the queue is not empty
            val current = getWidget(currentKey)  // get the element at the front
            val newQueueItems =                  // filter out the dependencies already known
              current.dependencies.filterNot(dependencyKey => 
                accumulator.exists(_.name == dependencyKey) && !queue.contains(dependencyKey))
            traverseTree(newQueueItems ::: queueTail, current :: accumulator) // 
          case Nil =>                            // the queue is empty
            accumulator.reverse                  // we're done
        }
      }
    
      traverseTree(key :: Nil, List[Widget]())
    }
    

    And test it out:

    for (k <- 1 to 5)
      println(getWidgetTree(k.toString).map(_.name))
    

    prints:

    ListBuffer(1, 2, 3, 4, 5)
    ListBuffer(2, 3, 4)
    ListBuffer(3)
    ListBuffer(4)
    ListBuffer(5)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am attempting to return a rowcount from a subquery as part of a
Attempting to use the data series from this example no longer passes the JSONLint
I am attempting to query entities with HQL in order to return a list
I'm currently attempting to retrieve a list of objects from my database using jQuery.
I am attempting to read the results from a SQL query into a List(Of)
I'm attempting to query an SSAS cube using MDX, I have a list of
I'm attempting to create a linked list of length n using Python. I have
I'm attempting to return a list of observers associated with a particular object using
I am attempting to return a collection of departments from a .NET assembly to
I have a list of RSS links/URLs on a page that I'm attempting to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.