Reputation: 23
I am new to Python and came across an old problem in HackerRank which defines a Binary Tree as such. I reviewed this video on classes and instances (and the next one) to try to understand what is happening in the below code but I still don't fully grasp what is going on.
__ init __(self, ...)
but I'm not sure what attribute info
has. I also do not understand why self.left = None
, self.right = None
, self.level = None
.BinarySearchTree
, there's an init with no attribute and I also do not understand the self.root = None
.Even though I don't understand most of the code below, I think if someone can explain why the person set self.____= None
, it would help me understand how to define a Binary Search Tree.
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, val):
if self.root == None:
self.root = Node(val)
else:
current = self.root
while True:
if val < current.info:
if current.left:
current = current.left
else:
current.left = Node(val)
break
elif val > current.info:
if current.right:
current = current.right
else:
current.right = Node(val)
break
else:
break
Upvotes: 1
Views: 273
Reputation: 89
If you try sketch your tree structure as a bunch of circles with some values inside, you will get something like that:
The 'info' attribute will contain the values that are inside of the circles. Every node of a binary tree can have at most two children, that's what the 'left' and 'right' attributes are used for. If the 'left' attribute is 'None', it basically means there is no child node on the left side yet (like in case of the node 16 on the image). If you create a new node, you usually do not expect it to have any children, that's why the 'left' and 'right' attributes are 'None' by default.
The class 'BinarySearchTree' represents a tree as a whole and keeps the current root node (the top one on the image) in the corresponding 'root' attribute. At the beginning the tree is empty, so the 'root' attribute equals to 'None'.
Hope it helps!
Upvotes: 2