Binary Tree implementation with Separate class for node and tree - python-3.x

I am new to Python and data structures. While learning binary tree, I found all the available implementations have the methods of the tree inside the node class.
But I want to implement it differently, where along with the Node class, there will be a Binary tree class, which will contain the methods of the Binary tree.
This is the code I came up with, but it raises an error with the arguments I am passing to the functions insertleft() and insertright().
class Node():
def __init__(self, arg):
self.left = None
self.right = None
self.data = arg
class Bt():
def __init__(self, root):
self.root = root
def insertleft(temp.left, data):
if (temp.left == None):
temp.left.data = data
elif(data<temp.left.data):
t1 = temp.left
insertleft(t1.left, data)
elif(data>temp.left.data):
t1 = temp.left
insertright(t1.left, data)
def insertright(temp.right, data):
if (temp.right == None):
temp.right.data = data
elif(data<temp.right.data):
t1 = temp.right
insertleft(t1.right, data)
elif(data>temp.right.data):
t1 = temp.right
insertright(t1.right, data)
def insert(self, data):
temp = self.root
if(temp.data = None):
temp.data = data
elif(data<temp.data):
insertleft(temp.left, data)
elif(data>temp.data):
insertright(temp.right, data)
r = Bt()
r.root = Node(5)
r.insert(4)
r.insert(6)
These is the error I received:
def insertleft(temp.left, data):
^
SyntaxError: invalid syntax
I am not sure what the right syntax should be. Thanks in advance for your help

When you define a function, you also define the parameters you will be accepting. Inside a class though, as long as the method is not static or a class method, the first parameter should be self or a variable that represents the instanciated object itself.
In your case, you are already passing the value of temp.left and temp.right when calling the function. Changing the function definitions to just use temp should work just fine. Or even more readible, node since that is what you are actually referring to.
Your insertleft and insertright functions do the same thing as insert, and including them is not necessary. Just modify the insert function to do it all.
Here's what the end result should resemble:
class Node():
def __init__(self, arg):
self.left = None
self.right = None
self.data = arg
class Bt():
def __init__(self, root=None): #Added default value
self.root = Node(root)
def insert(self, data):
if self.root.data is None:
self.root.data = data #Set the root data if it doesn't exist.
else:
self._insert(self.root, data) #Prime the helper function with root node
def _insert(self, node, data): #Insert helper function to do the insertion
if data < node.data: #Check if data needs to be inserted on the left
if node.left is None: #Set left node if it doesn't exist
node.left = Node(data)
else: #Else let the left node decide where it goes as a child
self._insert(node.left, data)
else: #Else data needs to be inserted on the right
if node.right is None: #Set right node if it doesn't exist
node.right = Node(data)
else: #Else let the right node decide where it goes as a child
self._insert(node.right, data)
r = Bt(5)
r.insert(4)
r.insert(6)
Now you're just missing functions to print the Tree and Data... and accessing the data.

Each Node in the binary search tree is considered as a another binary search tree. Hence we don't need to create a separate class for node.

Related

Defining a global variable inside a class vs. defining inside a method

I am trying to find the vertical width if a binary tree as defined in this link; https://practice.geeksforgeeks.org/batch/dsa-4/track/DSASP-Tree/problem/vertical-width-of-a-binary-tree
My question is regarding defining a global variable inside a class vs defining it inside a method. Here is my code, which is working as expected in the present form;
class Node:
#global dnew
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def vertical_width(self):
#dnew = {self.data: 0}
#print(self.data, dnew)
if self is None:
return
# if we move left decrease value by 1
if self.left != None:
dnew[self.left.data] = dnew[self.data] - 1
self.left.vertical_width()
print('left', dnew)
# if we move right increase value by 1
if self.right != None:
dnew[self.right.data] = dnew[self.data] + 1
self.right.vertical_width()
print('right', dnew)
return dnew
def mainfn(self):
global dnew
dnew = {self.data:0}
result = self.vertical_width()
return len(set(result.values()))
class Tree:
def __init__(self,root):
self.root = root
# define a tree as an example to test the code
node = Node(1)
node.left = Node(2)
node.left.left = Node(3)
node.left.right = Node(4)
node.right = Node(5)
#node.right.left = Node(6)
mytree = Tree(node)
res = mytree.root.mainfn()
Question is, if we just define global dnew inside the Node class rather than defining it inside the mainfn(), we get following error message;
NameError: name 'dnew' is not defined
But isn't that if we define a variable with global keyword, it shd be accessible by all methods in a class.Can I please get some help to understand this concept?

Wrapper Class in Python for Linked List

I am absolutely new to Wrapper Classes in Python. I was trying to implement it in a program of linked list where multiple linked list are in use. My code is:
def nodewrap(cls):
class Nodewrap:
def __init__(self):
self.head = None
self.tail = None
return Nodewrap
#nodewrap
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Intersection:
def addnode(self,d):
newnode = Node(d)
if head == None:
head = tail = newnode
else:
tail.next = newnode
tail = newnode
obj1 = Intersection()
obj2 = Intersection()
obj3 = Intersection()
s1 = int(input("Enter size of 1st list : \n"))
for i in range(s1):
obj1.addnode(int(input("Enter the data : \n")))
s2 = int(input("Enter size of 1st list : \n"))
for i in range(s2):
obj2.addnode(int(input("Enter the data : \n")))
temp1 = obj1.head
for i in range(s1):
temp2 = obj2.head
for j in range(s2):
if temp1.data == temp2.data:
obj3.addnode(temp1.data)
break
temp2 = temp2.next
temp1 = temp1.next
print("Intersection is :")
temp = obj3.head
while temp!=None:
print(temp.data,end=" ")
temp = temp.next
I thought of using a wrapper class to wrap the class Node instead of using objects of the class Intersection only with data fields as head, tail. But it is giving me some sort of error with regards to init().
Please help.
I was trying to learn it from here:
https://www.geeksforgeeks.org/wrapper-class-in-python/
I think I understand what you want to do, but I think that you don't want to use a decorator, but you want to inherit from NodeWrap class
class Nodewrap:
head = None
tail = None
class Node(NodeWrap):
def __init__(self,data):
self.data = data
self.next = None
But I don't see any reason why to inherit this way. This should be enough, for a linked list. I have added is_first and is_last property
from __future__ import annotations
class Node:
prev_node = None
next_node = None
def __init__(self, data):
self.data = data
def add_node(self, node: Node) -> None:
if self.prev_node is not None:
raise ValueError('Previous node already defined.')
self.next_node = node
node.prev_node = self
#property
def is_first(self) -> bool:
return self.prev_node is None
#property
def is_last(self) -> bool:
return self.next_node is None
You can implement next, iter and create an Iterator class.
I don't recommend using next as the variable name.
from __future__ import annotations reference here. It's just for self reference annotation.

Traversal of a binary tree: i cannot get right output in python

I am typing pre-order traversal and the output is just '1-'; I have looked through several other threads on this site but cannot seem to find my mistake. Any hints or suggestions would be appreciated!
class Node(object):
def __init__(self, value):
self.number = value
self.left = None
self.right = None
class binarytree(object):
def __init__(self, root):
self.root = Node(root)
def print_traversal(self, direction, start):
if direction == 'pre_order':
return self.pre_order(start, '')
def pre_order(self, start, traversal):
if start:
traversal += (str(start.number) + '-' )
self.pre_order(start.left, traversal)
self.pre_order(start.right, traversal)
return traversal
# main function
tree1 = binarytree(1)
tree1.root.left = Node(2)
tree1.root.right = Node(3)
tree1.root.left.left = Node(4)
tree1.root.left.right = Node(5)
tree1.root.right.left = Node(6)
print(tree1.print_traversal('pre_order', tree1.root))```
The line
traversal += (str(start.number) + '-' )
assigns a new value to the local variable traversal; it does not modify the string already in traversal. Thus, the changes made in the recursive calls are never seen at the level above where they're made.

Most efficient way to query in a data tree that does not have proper indexing

Pardon me if the terminology of the title is wrong. Let me illustrate what I mean:
I have a data tree for a basic educational course. Every node holds 2 values(apart from children and parent data): ID and a bool value. I can not change the ID value since I am fetching it from an API so I can not form my data tree as a binary tree. That is what I mean by "does not have proper indexing".
BTW: ID is random.
As you can see, I am structuring my tree with a hierarchy. Courses are supersets of episodes and episodes are supersets of topics.
My question:
I want to gather some data from a specific topic node. I know it is a topic node and I know its id. How do I find that node to get some data out of it most efficiently?
When I researched about tree data structures, they usually index their nodes with some sort of rule (ex: binary trees), I am not sure I can do that since I want to preserve the hierarchy of data types. If there is a way that I can both keep some sort of indication of hierarchy and order my trees for many efficient queries. I am happy to do that. I don't want to brute force if possible
You can combine the usual Node class approach with a dictionary which you maintain at tree instance level.
For instance:
class Node:
def __init__(self, id, name, boolval):
self.id = id
self.name = name
self.boolval = boolval
self.children = []
def tolist(self): # utility method for simple visualisation
if not self.children:
return [self.name]
else:
return [self.name, [child.tolist() for child in self.children]]
class Tree:
def __init__(self):
self.dict = dict() # this will map id to node
self.root = None
def append(self, id, name, boolval, parentid=""):
node = Node(id, name, boolval)
self.dict[id] = node
if self.root:
parent = self.get(parentid)
parent.children.append(node)
else:
self.root = node
def get(self, id):
return self.dict[id]
def tolist(self):
if not self.root:
return
return self.root.tolist()
# demo use:
tree = Tree()
tree.append("ab12", "Tree", False)
tree.append("ab13", "Physics", False, "ab12")
tree.append("a4d5", "Math", False, "ab12")
tree.append("524d", "Section A", False, "a4d5")
# ...etc
print(tree.tolist())
If you need to know from a given node what its hierarchy is, then add parent references:
class Node:
def __init__(self, id, name, boolval):
self.id = id
self.name = name
self.boolval = boolval
self.children = []
self.parent = None
def path(self):
if self.parent:
return self.parent.path() + [self.id]
return [self.id]
def tolist(self): # utility method for simple visualisation
if not self.children:
return [self.name]
else:
return [self.name, [child.tolist() for child in self.children]]
class Tree:
def __init__(self):
self.dict = dict() # this will map id to node
self.root = None
def append(self, id, name, boolval, parentid=""):
node = Node(id, name, boolval)
self.dict[id] = node
if self.root:
parent = self.get(parentid)
parent.children.append(node)
node.parent = parent
else:
self.root = node
def get(self, id):
return self.dict[id]
def tolist(self):
if not self.root:
return
return self.root.tolist()
# demo use:
tree = Tree()
tree.append("ab12", "Tree", False)
tree.append("ab13", "Physics", False, "ab12")
tree.append("a4d5", "Math", False, "ab12")
tree.append("524d", "Section A", False, "a4d5")
# ...etc
print(tree.tolist())
print(tree.get("524d").path()) # ['ab12', 'a4d5', '524d']

binary search tree - recursive insertion python

I'm trying to correctly construct a binary search tree with a recursive insert function that will allow me to initialize a tree and continue to add nodes (stems). Here is the code that I've done so far (newer to coding, so probably way too wordy):
class Binary_Search_Tree:
class __BST_Node:
def __init__(self, value):
self.value = value
self.right_child = None
self.left_child = None
def __init__(self):
self.__root = None
self.__height = 0
self.value = None
def _recursive_insert(self, value):
new_stem = Binary_Search_Tree.__BST_Node(value)
if self.__root is None:
self.__root = new_stem
self.__root.value = new_stem.value
else:
if self.__root.value > new_stem.value:
if self.__root.right_child is None:
self.__root.right_child = new_stem
self.__root.right_child.value = new_stem.value
else:
self.__root.right_child._recursive_insert(self.__root, value)
else:
if self.__root.left_child is None:
self.__root.left_child = new_stem
self.__root.left_child.value = new_stem.value
else:
self.__root.left_child._recursive_insert(self.__root, value)
def insert_element(self, value):
element_to_insert = self._recursive_insert(value)
return element_to_insert
I then try to add values to this new tree in the main method:
if __name__ == '__main__':
new = Binary_Search_Tree()
new.insert_element(23)
new.insert_element(42)
new.insert_element(8)
new.insert_element(15)
new.insert_element(4)
new.insert_element(16)
The error that I keep getting is: '__BST_Node' object has no attribute '_recursive_insert' This pops up after inserting the first element, so I'm guessing the error occurs somewhere in the else statement. If anyone can figure out where my error is or has any tips on how to make this code more readable/user friendly, I'd be appreciative!
The issue is with this line:
self.__root.right_child._recursive_insert(self.__root, value)
As well as this:
self.__root.left_child._recursive_insert(self.__root, value)
You've defined _recursive_insert to be a method of Binary_Search_Tree, but you're calling it with an instance of __BST_Node, in self.__root.xxxxx_child._recursive_insert, where xxxx_child is an instance of BST_Node.
In fact, your entire _recursive_insert function leaves something to be desired. You're not returning anything from it, but you are assigning it's (non-existent) return value to something in insert_element.
Fixed code:
def _recursive_insert(self, root, value):
new_stem = Binary_Search_Tree.__BST_Node(value)
if root is None:
root = new_stem
else:
if root.value < new_stem.value:
if root.right_child is None:
root.right_child = new_stem
else:
root = self._recursive_insert(root.right_child, value)
elif root.value > new_stem.value:
if root.left_child is None:
root.left_child = new_stem
else:
root = self._recursive_insert(root.left_child, value)
return root
def insert_element(self, value):
self.__root = self._recursive_insert(self.__root, value)
return element_to_insert
Your function did not return an updated root
Your function does not handle a case when the value being inserted would be equal to an existing value, causing spurious entries.
With each recursive call, your function was being passed the same values, so it would not be able to know what to do. A new parameter for the node must be passed across calls. This makes it possible to establish a base case and return.

Resources