tree in python data structure

Exploring Tree Data Structure in Python | Python Course in Delhi

The tree data structure is a great tool in the memory allocation and programming. It is a method of organization and storing of data in a hierarchical manner. It includes the central node, structural nodes, and sub-nodes interconnected by edges. This type of structure makes various tasks including data retrieval, data manipulation, and algorithm design smoother. This is why it is a necessity in many applications such as database management. Learn about tree data structure in this article by a trainer from python institute in Delhi

Basics of Tree Data Structure in Python

Below are the basic terms in tree data structure: 

  • Parent Node: The node that comes before the other node is called the parent node. For eg: Node {B} is the parent of the nodes {D, E}. 
  • Child Node: The immediate successor of the node is a child node. For eg: Nodes {D, E} are children of node {B}.
  • Root Node: The highest level node of a tree lacking a parent is the root node. For example, node {A}.
  • Leaf Node or External Node: All nodes without children are referred to as leaf nodes. For eg: {K, L, M, N, O, P, G}.
  • The ancestor of a Node: All nodes that precede the given node on a path leading to the root are its ancestors. For eg: Nodes {A, B} are ancestors of {E} nodes.
  • Descendant: Node x is a descendant of node y if y is an ancestor of xa.
  • Sibling: Children have the same parent node as siblings. Example: Nodes {D, E} are brothers.
  • Level of a Node: The number of edges from the root node to the one in question. The root node is at the level of 0.
  • Internal Node: A node with one or more children is an internal node.
  • Neighbour of a Node: A given node’s parent and child nodes are its neighbouring nodes.
  • Subtree: Any given node with its children.

Learn about linked list in python

Types of Tree Data Structure

Here are several types of tree data structures that serve distinct purposes in computer science:

  • General Tree: It enables the nodes to have an unlimited number of children. This is frequently employed in the virtual structure of computer file systems.
  • Binary Tree: Under this structure the nodes can have two children each. It promotes effective data presentation and retrieval.
  • Binary Search Tree (BST): Adheres to a set of rules stating that the left child values are less than the parent and the right child values are greater.  It makes the data search and manipulation process quicker.
  • AVL Tree: Self-balancing BST that automatically adjusts height for the best performance. It is the perfect one when large data insertion and lookup operations are conducted frequently.
  • Red-Black Tree: It is another self-balancing BST where the tree balances through colour-coded nodes. This one is widely used in computational geometry.
  •  Splay Tree: Self-adjusting BST is the most used option for cache implementation and garbage collection which results in efficient data retrieval.
  • B-Tree: Self-adjusting search tree, which is the best for large-scale storage systems like file systems and databases. It makes the time-consuming data sorting and retrieval process easy.
  • Treap Tree: Combinations of the BST and heap, with the randomization of the data organization for the efficient management of the data.

Tree Applications

Tree data structures find extensive applications across various domains, It showcase their versatility and significance in computer science and beyond:

  • Binary Search Trees (BSTs): These are the ones that help quickly find an element in a given set. They make the search operations very fast.  
  • Heaps: These are a kind of tree mostly used for heap sort algorithms, which in turn, makes data sets sorting fast and efficient.
  • Tries: The updated versions of trees such as Tries are used in modern routers for storing routing information. It improves the network performance and scalability.
  • Database Management: Main databases use variants of tree structures like B-Trees and T-Trees to make the management and organisation of their huge databases efficient and reliable. 
  • Compiler Design: Through syntax trees, compilers make sure that the syntax of every program is correct. It follows the rules of the programming language.

Implementation of Tree

The tree data structure is created dynamically by the creation of nodes and their linking through pointers. In memory, a tree is represented with each node containing three fields: which is the data itself and the pointers to its left and right children. 

inserting data in tree in python

The diagram shows this way of memory representation. The architecture of a node in programming usually consists of the data field and pointers to the left and right children. Nevertheless, for binary trees, which can have at most two children, this structure is enough. For the common trees with more than two children, there is a different node structure. Below is a basic structure definition for a binary tree in programming:

class Node:
   def __init__(self, data):
      self.left = None
      self.right = None
      self.data = data
   def PrintTree(self):
      print(self.data)

root = Node(20)
root.PrintTree()

Inserting a node is like:

class Node:
   def __init__(self, data):
      self.left = None
      self.right = None
      self.data = data

   def insert(self, data):
# Compare the new value with the parent node
      if self.data:
         if data < self.data:
            if self.left is None:
               self.left = Node(data)
            else:
               self.left.insert(data)
         elif data > self.data:
               if self.right is None:
                  self.right = Node(data)
               else:
                  self.right.insert(data)
      else:
         self.data = data

# Print the tree
   def PrintTree(self):
      if self.left:
         self.left.PrintTree()
      print( self.data),
      if self.right:
         self.right.PrintTree()

# Use the insert method to add nodes
root = Node(112)
root.insert(622)
root.insert(11)
root.insert(22)
root.PrintTree()

Why Use Tree Data Structures?

Tree data structures are very useful because of their flexibility and their ability to organize and handle hierarchical data in a fast way. A notable feature is their capability to show the hierarchical relationships intuitively. Plus they are the perfect tools for storing such as file systems, organizational charts and family trees. 

This sort of hierarchy allows for the smooth operation of search and retrieval, important for tasks like searching for files in a directory or locating a specific element in a database. Trees also let you choose from several algorithms and data structures, like binary search trees, AVL trees, and B-trees. Each algorithm is designed for a specific operation like searching, insertion or deletion. 

Furthermore, tree structures are balanced and they provide a steady performance with large datasets. It reduces the possibility of a performance slowdown. Besides this, trees are also used in other areas, for example, decision-making processes, decision trees in machine learning algorithms, and efficient routing mechanisms in computer networks.

You can learn more about data structure in Python and its practicals in our python course institute in Delhi

Call Now Button