0

I am trying to get a list of values of the tree using DFS but I only get root's value. :(

def depthFirstSearch(root):
    output = []
    if root:
        output.append(root.value)
        depthFirstSearch(root.left)
        depthFirstSearch(root.right)
    return output
fravolt
  • 2,565
  • 1
  • 4
  • 19
Moon
  • 1

1 Answers1

0

A bit late perhaps, but if you look at what you do it makes sense that only your root is returned.

Specifically, you append the root.value in the first iteration, then you run depthFirstSearch for both children (in a binary tree, presumably), but here's the thing: You just discard the result. It will probably work if you concatenate the results from both recursive calls to the output before returning.

That would get you something like:

def depthFirstSearch(root):
    output = []
    if root:
        output.append(root.value)
        # use the += operator to concatenate the current output list and the new one from the subtree
        output += depthFirstSearch(root.left)
        output += depthFirstSearch(root.right)
    return output
fravolt
  • 2,565
  • 1
  • 4
  • 19