Binary Tree Implementation (OOP)
Binary Tree Implementation (OOP)
Worked Example: 9618 Paper 4 Question : 9618_s25_qp_41
Task: Create a class
Node to represent a binary tree that stores integers in ascending numerical order. Implement the constructor and the Get/Set methods as defined in the provided specification table.
class Node:
# Constructor()
def __init__(self, data_value):
# Initialises NodeData to parameter value
self.__NodeData = data_value
# Initialises LeftNode and RightNode to a null value
self.__LeftNode = None
self.__RightNode = None
# GetLeft() returns LeftNode
def get_left(self):
return self.__LeftNode
# GetRight() returns RightNode
def get_right(self):
return self.__RightNode
# GetData() returns NodeData
def get_data(self):
return self.__NodeData
# SetLeft() takes a Node object and stores it in LeftNode
def set_left(self, node_object):
self.__LeftNode = node_object
# SetRight() takes a Node object and stores it in RightNode
def set_right(self, node_object):
self.__RightNode = node_object
# --- Example Usage (Building the tree in the diagram) ---
root = Node(30)
root.set_left(Node(20))
root.set_right(Node(45))
# Accessing data
print(root.get_left().get_data()) # Outputs: 20
💡 Tech Insight for Students:
Notice the use of self.__Attribute. In Python, the double underscore is how we implement Encapsulation (Private variables). This ensures that the only way to change a node's children is through the SetLeft() and SetRight() methods, preventing accidental data corruption.