Binary Tree



A basic implementation of a binary tree structure.

A binary tree is basically a structure with nodes connected by edges. Each node has a maximum of two children, which are usually called as the left child node and the right child node. The first node of the tree is commonly referred to as the root.

binary tree 01

The structure of our binary tree will be divided in 2 classes (Node and BinaryTree) and 1 builder function (BuildTree).

Node class


The Node class is responsible for storing the node data (or the node value) and referring (or not) to child nodes that will be connected to its left and right edges. So, the node class will have 3 attributes: data, left and right.

Binary tree class


The BinaryTree class has just 1 attribute, which is the root. This attribute is a Node object and starts the chain of Node object that will compound the tree itself. The print method is based on level-order traversal algorithm, but it will be covered in another notebook.

Building the binary tree


The BuildTree function receive 2 arguments. The first one is the root of a BinaryTree object and the second is the list of pair values (left and right) for each node. The first pair is the left and right of the root and other ones are respective to the other nodes, following the top/down and left/right order. If the pair has -1 as value, it means the current node has no child in this edge (this happens always with leaf nodes).

binary tree 02

For example, having the following binary tree:

binary tree 03

The build function would be: