Tree

A tree is a non-linear but hierarchical data structure. The topmost element is known as the root of the tree since the tree is believed to start from the root. The elements at the end of the tree are known as its leaves. Trees are appropriate for storing data that aren’t linearly connected to each other but form a hierarchy. 

Program:

Python3




class node:
    def __init__(self, ele):
        self.ele = ele
        self.left = None
        self.right = None
 
 
def preorder(self):
    if self:
        print(self.ele)
        preorder(self.left)
        preorder(self.right)
 
 
n = node('first')
n.left = node('second')
n.right = node('third')
preorder(n)


Output:

first

second

third

User Defined Data Structures in Python

In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures:

  • Non-primitive data types: Python has list, set, and dictionary as its non-primitive data types which can also be considered its in-built data structures.
  • User-defined data structures: Data structures that aren’t supported by python but can be programmed to reflect the same functionality using concepts supported by python are user-defined data structures. There are many data structure that can be implemented this way:

Similar Reads

Linked list

A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:...

Stack

...

Queue

A stack is a linear structure that allows data to be inserted and removed from the same end thus follows a last in first out(LIFO) system. Insertion and deletion is known as push() and pop() respectively....

Tree

...

Graph

A queue is a linear structure that allows insertion of elements from one end and deletion from the other. Thus it follows, First In First Out(FIFO) methodology. The end which allows deletion is known as the front of the queue and the other end is known as the rear end of the queue....

Hashmap

...

Contact Us