Inorder Traversal of Tree in Python Returning a List
Asked Answered
H

4

8

I learnt implementing inorder traversal of a binary search tree:

def inorder(root): # root has val, left and right fields
    if root==None:
        return

    inorder(root.left)
    print(root.val)
    inorder(root.right)

Now, the problem is I do not want console output. I want to get the values in a list. I can't find a way to make the function return a list.

I tried s = [inorder(root)] but it doesn't work.

So, my question is:

  1. Any way this could be done inside the inorder function, i.e. it should return a list rather than just print values.

  2. Is there some generic way to make recusive functions return data structures instead of just outputting a print to console?

Hombre answered 2/3, 2018 at 5:52 Comment(0)
G
10

You can build up the list recursivly. Simply add the returned list from the left and right trees together with the value in the current node.

def inorder(root):
    if root==None:
        return []

    left_list = inorder(root.left)
    right_list = inorder(root.right)
    return left_list + [val] + right_list 
Gunshy answered 2/3, 2018 at 6:5 Comment(0)
A
4

You can pass a list, and then append the values to it, like this-

def inorder(root,ans): # root has val, left and right fields
    if root==None:
        return

    inorder(root.left)
    ans.append(root.val)
    inorder(root.right)
ans=[]
inorder(root,ans)
print(ans)

Answering your second query:

Passing the data structure itself is the simplest solution. If you really want the function to "return" the output, One way is using list concatenation as @Shaido suggested, but it is slightly heavier on memory by unnecessarily creating a new singleton list at every recursive call.

A better solution would be using some static list(i. e. a fixed list that would be declared only once). But it's not available directly in python, because python suggests doing it by declaring it inside a class. (A good discussion here)

Aundrea answered 2/3, 2018 at 6:2 Comment(0)
R
1
def inorder(root, arr):

    if root is None:
        return
    arr.append(root.val)
    traverse(root.left, arr)
    traverse(root.right,arr)
    return arr


inorder_list = inorder(root, [])

Happy Coding :)

Reinaldo answered 19/6, 2020 at 7:23 Comment(2)
Welcome to Stack Overflow! Code-only answers are not particularly helpful. Please include a brief description of how this code solves the problem.Talich
could you please share, more details about your answer, to make it understandable or how does it resolve the question...Tautomerism
W
1

I was having similar issue like yours a while ago. A workaround that I came up with was to create a utility function where you pass a list. This list will be filled by the time the recursion is done.

Now, in your main function, you simply invoke the utility function with your root node and an empty list as your parameters. I hope that was helpful. Cheers!

def preorderTraversal(self, root: TreeNode) -> List[int]:
        result = []
        self.preorder(root, result)       
        return result
    
def preorder(self, node, arr):
        if not node:
            return
        arr.append(node.val)
        self.preorder(node.left, arr)
        self.preorder(node.right, arr)
Wigwam answered 26/6, 2020 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.