What is Tree?

<aside> 💡 Tree is a non-linear data structure but hierarchy. The element that is on the top is known as root Tree because Tree is believed originally from root. The elements in the edge of Tree are called by leaf.

</aside>

Untitled

Tree that is suitable to store the data that is not connected but is linear to each other but in a form of hierarchy.

In Python, a node is an essential building block used in various data structures. Let’s explore what nodes are and how they are implemented:

  1. Node Basics:
  2. Python Node Implementation:

Here’s an example implementation of a Node class in Python:

class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next_node = next_node

    def set_next_node(self, next_node):
        self.next_node = next_node

    def get_next_node(self):
        return self.next_node

    def get_value(self):
        return self.value

Feel free to use this Node class to create linked lists or other data structures in your Python programs! 🌟

For more details and examples, you can refer to the Codecademy Cheatsheet on Nodes1.

Implementation

# Tree
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)
first
second
third