Index      Binary Tree  Problems  Change Language   Source
1class Node:
2    def __init__(self, data):
3        self.left = None  # chap
4        self.right = None  # rast
5        self.data = data

Binary Tree

The structure of a binary tree is similar to a regular tree but leveled. Levels start from zero, where only one vertex called the root exists at level zero. Any two vertices connected by an edge reside in exactly two consecutive levels. Consider two vertices u and v connected by an edge where u is in the lower-numbered level. We call u the parent of v, and v the child of u. In this graph, each vertex has at most two children and clearly has one parent. Vertices with no children are called leaves. The longest path among all paths from the root to a leaf is called the height. A subtree refers to a subgraph of the binary tree where if vertex u is included, all its children must also be included.

Binary Tree

In this section, we will discuss three types of binary trees.

Full Binary Tree

A binary tree in which all vertices either have two children or are leaves.

Full Binary Tree

Complete Binary Tree

A binary tree where all leaves are in the last two levels, and the leaves of the last level are filled from the left.

Complete Binary Tree

Perfect Binary Tree

A tree where all leaves are at the last level and all nodes in other levels have two children is called a perfect binary tree.

Perfect Binary Tree

One of the most common uses of binary trees is the binary search tree, which we will examine in more detail later.