The Tree data structure is similar to linked lists in that each node contains data and can be linked to other nodes. In a Tree, a single element can have multiple ‘next’ elements, allowing the data structure to branch out in various directions. The data structure is called a “tree” because it looks like a tree, only upside down. The Tree data structure can be useful in many cases:
Trees are a fundamental data structure in computer science, used to represent hierarchical relationships.
Binary Trees: Each node has up to two children, the left child node and the right child node. This structure is the foundation for more complex tree types like Binay Search Trees and AVL Trees.
Binary Search Trees (BSTs): A type of Binary Tree where for each node, the left child node has a lower value, and the right child node has a higher value.
AVL Trees: A type of Binary Search Tree that self-balances so that for every node, the difference in height between the left and right subtrees is at most one. This balance is maintained through rotations when nodes are inserted or deleted.
A Binary Tree is a type of tree data structure where each node can have a maximum of two child nodes, a left child node and a right child node. This restriction, that a node can have a maximum of two child nodes, gives us many benefits:
There are different variants, or types, of Binary Trees worth discussing to get a better understanding of how Binary Trees can be structured. Below are short explanations of different types of Binary Tree structures.
To avoid the cost of all the shifts in memory that we get from using Arrays, it is useful to implement Binary Trees with pointers from one element to the next, just like Binary Trees are implemented before this point, especially when the Binary Tree is modified often. But in case we read from the Binary Tree a lot more than we modify it, an Array implementation of a Binary Tree can make sense as it needs less memory, it can be easier to implement, and it can be faster for certain operations due to cache locality.
Consider this Binary Tree:
This Binary Tree can be stored in an Array starting with the root node R on index 0. The rest of the tree can be built by taking a node stored on index i, and storing its left child node on index 2⋅i + 1, and its right child node on index 2⋅i + 2. Below is an Array implementation of the Binary Tree. By comparing how these traversals are done in an array implementation to how the pointer implementation was traversed, you can see that the pre-order, in-order, and post-order traversals works in the same recursive way.
1 | binary_tree_array = ['R', 'A', 'B', 'C', 'D', 'E', 'F', None, None, None, None, None, None, 'G'] |
Algorithm, Binary Trees, Python — Jan 8, 2023
Made with ❤️ and ☀️ on Earth.