desert_ranger
desert_ranger

Reputation: 1741

How can I return an inorder traversal instead of just printing it

As of now, my code only prints out an in-order traveral. However, I would like it to return one.

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
def inorder(node):
    if(node==None):
        return
    else:
        inorder(node.left)
        print(node.data)
        inorder(node.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

P.S I know this tree is not a binary search tree.

Upvotes: 0

Views: 101

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21619

You can use generators. yield from the recursive calls and yield the data value.

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
def inorder(node):
    if node:
        yield from inorder(node.left)
        yield node.data
        yield from inorder(node.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print(list(inorder(root)))

result

[4, 2, 5, 1, 3]

If you wanted it to use a list and not generators.

def inorder_list(node):
    accum = []
    inorder_list_impl(node, accum.append)
    return accum

def inorder_list_impl(node, accumulator):
    if node:
        inorder_list_impl(node.left, accumulator)
        accumulator(node.data)
        inorder_list_impl(node.right, accumulator)

You could also use

inorder_list_impl(root, print)

To just print the values.

Upvotes: 1

Related Questions