Skip to main content
Question Protected by gnat
rephrase title so it's grammatically correct
Link

How todo I traverse a tree without using recursive function callsrecursion?

Tweeted twitter.com/#!/StackProgrammer/status/429064730524000256
Source Link
Reactgular
  • 13.1k
  • 4
  • 50
  • 82

How to traverse a tree without using recursive function calls

I have a very large in memory node tree and need to traverse the tree. Passing the returned values of each child node to their parent node. This has to be done until all the nodes have their data bubble up to the root node.

Traversal works like this.

private Data Execute(Node pNode) { Data[] values = new Data[pNode.Children.Count]; for(int i=0; i < pNode.Children.Count; i++) { values[i] = Execute(pNode.Children[i]); // recursive } return pNode.Process(values); } public void Start(Node pRoot) { Data result = Execute(pRoot); } 

This works fine, but I'm worried that the call stack limits the size of the node tree.

How can the code be rewritten so that no recursive calls to Execute are made?