Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to create and print a binary tree in Python

1 Answer

0 votes
class Tree(object):
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None

root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"

root.left.left = Tree()
root.left.left.data = "left left"
root.left.right = Tree()
root.left.right.data = "left right"

root.right.right = Tree()
root.right.right.data = "right right"


def print_tree(tree_root):
    current_level = [tree_root]
    while current_level:
        print(" : ".join(str(node.data) for node in current_level))
        next_level = list()
        for n in current_level:
            if n.left:
                next_level.append(n.left)
            if n.right:
                next_level.append(n.right)
            current_level = next_level


print_tree(root)


'''
run:
   
root
left : right
left left : left right : right right
 
'''

 



answered Jun 27, 2018 by avibootz

Related questions

1 answer 151 views
1 answer 108 views
108 views asked Jun 14, 2023 by avibootz
1 answer 152 views
1 answer 153 views
2 answers 217 views
1 answer 91 views
...