If I was doing this in a higher level language I could either use recursion…
size(node):
1 + size(node.left) + size(node.right)
or iteration…
size = 0
stack = new Stack()
stack.push(root)
while(!stack.isEmpty()):
size++
node = stack.pop()
stack.push(node.left)
stack.push(node.right)
I’m not sure where to begin implementing either of these in assembly. Is it similar to a high level language, where recursion is more elegant but often less efficient (without tail recursion optimisation)?
Would I have to use the stack, or could I do this with a loop that only modifies registers? I need to actually count the nodes – not just keep a counter as they are added.
The nodes are stored in memory using two pointers and a data value, where the pointers refer to memory addresses storing children.
I’m using the QtSpim emulator if that makes any difference to the approach.
Also, I’m not asking for completed code (if any code..) just how I should approach the problem. I know how tree traversal works, but I’m struggling to see how it’s done in assembly.
Nothing prevents you from using either approach. I don’t see any difference between them. However, there’s a tree traversal algorithm which runs in O(1) memory so it doesn’t use recursion and stack. You can read more about it here: https://sites.google.com/site/debforit/efficient-binary-tree-traversal-with-two-pointers