0
def sum(root):
    if root.children == []:
        return root.value
    else:
        temp = 0
        for n in root.children:
            temp += sum(n)
        temp+= root.value
    return temp

I got my function to work recursively and am trying to figure out an easy way to do it iteratively. I just am trying to find guidance as to if I would be using a while loop or what.

2
  • 1
    I would recommend looking into Breadth First Search. Generally, you want to do Depth First Search recursively and Breadth First Search iteratively. Commented Jan 23, 2017 at 21:18
  • 1
    Traversing a tree is one of the cases where a recursive solution is by far the easiest one. Doing this iteratively would be much more complicated, for no benefit at all. Commented Jan 23, 2017 at 21:25

1 Answer 1

4

Use a queue or stack; take an element from your queue or stack, add the value to the running total, add any children to the queue or stack, then process the next element. Use a while loop that ends when your queue or stack is empty.

The only difference between a stack and a queue is that you'll either process your elements depth first (stack) or breath first (queue).

Your recursive code is depth-first, so to replicate the same behaviour iteratively, use a stack:

def sum_nodes_iteratively(root):
    elements = [root]
    total = 0
    while elements:
        element = elements.pop()
        elements.extend(element.children)
        total += element.value
    return total

Demo:

>>> class Node(object):
...     def __init__(self, value, children):
...         self.value = value
...         self.children = children
...
>>> def sum_nodes_iteratively(root):
...     elements = [root]
...     total = 0
...     while elements:
...         element = elements.pop()
...         elements.extend(element.children)
...         total += element.value
...     return total
...
>>> sum_nodes_iteratively(Node(1,[Node(2,[]),Node(3,[Node(4,[Node(5,[]),Node(6,[Node(7,[])])])])]))
28
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I forgot about using stack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.