Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a Binary Tree using __iter__

I have a standard Binary Tree that reads like
1
/ \
2 3
/ \ / \
4 5 6 7

I need to read the binary tree by importing my tree class, creating this tree, and then using a for loop to read it like: [4, 2, 5, 1, 6, 3, 7]

I have already made the tree and my program will generate a like tree with any amount of numbers. My problem is in the method.

def iter(self):

So far I have:

def __iter__(self):
    if self.left:
        self.left.__iter__()
    yield self
    if self.right:
        self.right.__iter__()

But when I run a for loop on the tree object like:

for item in tree: print("{}: {}").format(item.name, item.height())

It only prints the first node in my try with a correct height.

My question is basically, how to print this binary tree using recursion?

like image 337
Quizzlesticks Avatar asked Jan 18 '26 15:01

Quizzlesticks


1 Answers

In Python >= 3.3, one can use the yield from x syntax for recursive iterators:

def __iter__(self):
    if self.left:
        yield from self.left
    yield self
    if self.right:
        yield from self.right

Edit: Python 3.3 support confirmed.

like image 157
Jashandeep Sohi Avatar answered Jan 21 '26 04:01

Jashandeep Sohi