Python-Tutorial-4


Binary-Trees with Python3

A binary tree is a tree structure with nodes where there is a left and a right element, and leaves at the extremity, where we can store a data element (here a number.)
We use an associating dictionary, where the keys are: Leaf, and Value, for the leaves, and Left and Right for the nodes.
$ python3
Python 3.11.2
>>> bin_tree_1 = {'Leaf': {'Value': 23} }
>>> bin_tree_2 = {'Leaf': {'Value': 49} }
>>> bin_tree_3 = {'Left': bin_tree_1, 'Right': bin_tree_2 }
>>> bin_tree_3
{'Left': {'Leaf': {'Value': 23}}, 'Right': {'Leaf': {'Value': 49}}}
>>> bin_tree_3['Left']
{'Leaf': {'Value': 23}}
>>> left = bin_tree_3['Left']
>>> left
{'Leaf': {'Value': 23}}
>>> left_leaf = left['Leaf']
>>> left_leaf['Value']
23


bin_tree_1 = {'Leaf': {'Value': 23} }
bin_tree_2 = {'Leaf': {'Value': 49} }
bin_tree_3 = {'Left': bin_tree_1, 'Right': bin_tree_2 }

def traverse_tree(tree):
  if 'Left' in tree:
    print(f"traversing left:")
    traverse_tree(tree['Left'])
  if 'Right' in tree:
    print(f"traversing right:")
    traverse_tree(tree['Right'])
  if 'Leaf' in tree:
    leaf = tree['Leaf']
    if 'Value' in leaf:
      v = leaf['Value']
      print(f"v = {v}")

traverse_tree(bin_tree_3)

In order to traverse a binary-tree, we have to traverse successively the left branch, and after the right branch.
$ python3 bin_tree_1.py
traversing left:
v = 23
traversing right:
v = 49

Nevertheless, I don't know what is the scalability of recursive calls in python.

Going Further

Next you can explore other kinds of trees, and other data-structures.

Usage Notice

© 2025 Florent Monnier
License for the tutorial parts:
license: FDL
License for the code parts:
To the extent permitted by law:
spdx=any

back to the table of contents
The Python Language