This hierarchical data structure, along with its variations, is widely used across entire computer science world. You’ll find it in compression algorithms, internet routers, AI and most importantly - during coding interviews. Dive into this article to quickly grasp the basics!
The basis of binary tree is a node - a “point”, which possesses both data (e. g. a number) and references to other nodes (in case of binary tree there are at most two: left child node and right child node). It’s basically nodes nested inside each other.
Implementation in Python
Take a look at function
show_tree_data. It’s using recursion to print all tree elements. Recursion can be extremely helpful during implementation and understanding of other data structures and algorithms, so be sure to check my article about Merge Sort, which has entire section dedicated to the study of recursion, using colorful stars and level ids.
class BinaryTreeNode: # Binary tree is made of nodes. Each node has both data and references to # its left child (also a node) and right child (also a node). def __init__(self, data, left_child=None, right_child=None): self.data = data self.left_child = left_child self.right_child = right_child # Be sure to check my article about recursion to fully understand this code! def show_tree_data(self): if self.left_child is not None: self.left_child.show_tree_data() if self.right_child is not None: self.right_child.show_tree_data() print(self.data) # Binary tree is basically nodes nested inside each other. binary_tree = BinaryTreeNode(data=10, left_child=BinaryTreeNode(data=21, left_child=BinaryTreeNode(data=52), right_child=BinaryTreeNode(data=70)), right_child=BinaryTreeNode(data=30, left_child=BinaryTreeNode(data=16))) binary_tree.show_tree_data()