<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>
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:
__init__(self, value, next_node=None)
: Initializes a node with a given value and an optional link to the next node.set_next_node(self, next_node)
: Sets the link to the next node.get_next_node(self)
: Returns the next node.get_value(self)
: Returns the value stored in the node.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.
# 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