I am too stupid to ask a question. A lot of literature mentioned that we need to compare the to-insert value with the value of "current Node".
So basically, my question is:
In order to insert a new Node into a tree, we need to enter a Node. Firstly, the tree has to check whether this Node is in it. If yes, then we need to enter a value, which will be compared and then inserted.
class BTree:
def __init__(self):
self.root = None
def isEmpty(self):
if not self.root:
print('tree is empty')
return self.root
def insert(self, Node, data):
if not self.isEmpty():
print('the tree is empty, now is inserting ROOT')
self.root = Node(data)
else:
current = self.root
parent = None
while True:
#search the Node in the tree#
#if it is in the tree, insert#
It is too complicated, isn't it? Because we need even implement the search algorithm in the while loop.
Could you please give me some suggestions?
Thanks
Related
I'm trying to add elements to a binary tree and print them in in-order.
I'm getting an error while adding an element: AttributeError: 'NoneType' object has no attribute 'left'
Please let me know where I have to make a change Below is the code
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def InorderTraversal(self):
if self.data is None:
return
self.left.InorderTraversal()
print(self.data)
self.right.InorderTraversal()
if __name__ == "__main__":
root = Node(1)
root.insert(2)
root.insert(3)
root.insert(4)
root.InorderTraversal()
I am Implementing Trees First time Doesn't Have any idea
You should check if a node has left & right children before recursing on them:
class Node:
...
def InorderTraversal(self):
if self.left: # if left child exists, then recurse on it
self.left.InorderTraversal()
print(self.data)
if self.right: # if right child exists, then recurse on it
self.right.InorderTraversal()
Result:
1
2
3
4
You need the Node to be a separate class which will be used by the Tree class.
The insert and inorder_traversals are operations you do on a tree and not on a node. This is kinda the first thing you should do.
There are already pretty good resources you can look at since I might not be able to explain in that kind of detail :
https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
Also, you need to read up a little on how recursion and the classes work in python as I see some mistakes that can be fixed.
You're recursively printing the inorder traversal but you're doing the checks on self.data and running on self.left and self.right . self is pointing to the same data and you need to pass the node you wanna process next in the recursive function.
Also, you need to check the None condition on the Node and not on the data. Basically the node doesn't exist and that means you've to return from there
The inorder code overall idea is correct but you're working with wrong variables and basically you'll end up with incorrect output (or infinite loop)
My suggestion is to read up some more on tree on geeksforgeeks to begin with!
I have written the program for Binary Search Tree but does not know how can i save it in the Django Database. How can i store it in the models:
from __future__ import print_function
class Node:
# Constructor to initialize data
# If data is not given by user,its taken as None
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
# __str__ returns string equivalent of Object
def __str__(self):
return "Node[Data = %s]" % (self.data,)
class BinarySearchTree:
def __init__(self):
self.root = None
While inserting values in a binary search tree, we first check whether the value is greater than, lesser than or equal to the root of the tree. We initialize current node as the root. If the value is greater than the current node value, then we know that its right location will be in the right subtree. So we make the current element as the right node.
If the value is lesser than the current node value, then we know that its right location will be in the left subtree. So we make the current element as the left node.
If the value is equal to the current node value, then we know that the value is already contained in the tree and doesn't need to be reinserted. So we break from the loop.
def insert(self, val):
if (self.root == None):
self.root = Node(val)
else:
current = self.root
while 1:
if (current.data > val):
if (current.left == None):
current.left = Node(val)
break
else:
current = current.left
elif (current.data < val):
if (current.right == None):
current.right = Node(val)
break
else:
current = current.right
else:
break
In preorder traversal, we first print the current element, then move on to the left subtree and finally to the right subree.
def preorder(self, node):
if (node == None):
return
else:
print(node.data, end=" ")
self.preorder(node.left)
self.preorder(node.right)
In inorder traversal, we first move to the left subtree, then print the current element and finally move to the right subtree.
#Important : Inorder traversal returns the elements in sorted form.
def inorder(self, node):
if (node == None):
return
else:
self.inorder(node.left)
print(node.data, end=" ")
self.inorder(node.right)
In postorder traversal, we first move to the left subtree, then to the right subtree and finally print the current element.
def postorder(self, node):
if (node == None):
return
else:
self.postorder(node.left)
self.postorder(node.right)
print(node.data, end=" ")
tree = BinarySearchTree()
tree.insert(1)
tree.insert(9)
tree.insert(4)
tree.insert(3)
tree.insert(5)
tree.insert(7)
tree.insert(10)
tree.insert(0)
print ("Preorder Printing")
tree.preorder(tree.root)
print("\n\nInorder Printing")
tree.inorder(tree.root)
print("\n\nPostOrder Printing")
tree.postorder(tree.root)
User can add and delete a tree and On adding a tree, user should be prompted to enter at least 3 nodes...
A binary search tree structure should be displayed when a tree is selected, with its
respective nodes in the order of insertion.....
How can all the changes that have been done by the user can be reflected back into the database..
I'm new to python and am trying to return the preorder list of an ordered tree (NOTE: Not Binary Tree). I'm having some trouble following the recursion after it reaches a leaf of the tree. How do I get it to go back up to the previous node? Here's my code thus far:
def OrdPreOrder(T):
if Is_OrdLeaf(T):
return []
else:
for t in Subtrees(T):
return [OrdRoot(t)] + OrdPreOrder(t)
Thanks in advance,
The question is not very clear to me, but hopefully this will help.
You want to do a pre-order traversal of an ordered tree.
Pre-Order traversal means
1. Firstly print the value stored in node
2. Then print the value stored in children (according to some principle)
First off,
How do I get it to go back up to the previous node?
According to the definition of pre-order traversal i have written above, I don't see why you need to go back and revisit the parent node.
class Node:
def __init__(self, data):
self.__data = data
self.__children = []
def identifier(self):
return self.__data
def children(self):
return self.__children
def add_child(self, data):
self.__children.append(data)
class Tree:
def __init__(self):
self.__nodes = {}
def nodes(self):
return self.__nodes
def add_node(self, data, parent=None):
node = Node(data)
self[data] = node
if parent is not None:
self[parent].add_child(data)
return node
def traversal(tree):
if tree == None:
return
print (tree.identifier())
for child in tree.children():
traversal(child)
I am also not that well versed with data structures in Python (there might be mistakes in the code). But hopefully it might point you in the right direction.
Below code is a simple implementation of BFS in Python. I able to print the values level by level from a tree. However when I want to search a element and print it . I am not able to do it. Whts is the error?
def search_bfs(self,root,key):
q=QueueClass()
q.enqueue(root)
while q.size() > 0:
curr_node = q.dequeue()
#print curr_node
#print key
if curr_node == key:
print curr_node
break
if curr_node.left is not None:
q.enqueue(curr_node.left)
if curr_node.right is not None:
q.enqueue(curr_node.right)
from QueueClass import QueueClass
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def __str__(self):
return str(self.data)
class searchtree:
def __init__(self):
self.root = None
def create(self,val):
if self.root == None:
self.root=Node(val)
else:
current=self.root
while 1:
if val < current.data:
if current.left:
current=current.left
else:
current.left=Node(val)
break
if val > current.data:
if current.right:
current=current.right
else:
current.right=Node(val)
break
else:
break
tree=searchtree()
lst=[3,1,2,6,4,5,8,12]
for i in lst:
tree.create(i)
tree.search_bfs(tree.root, 3)
You really make it hard to reproduce your problem! So here's what I did:
class QueueClass(object):
def __init__(self):
self.l = []
def size(self): return len(self.l)
def enqueue(self, it): self.l.append(it)
def dequeue(self): return self.l.pop()
class Node:
def __init__(self, name, left=None, right=None):
self.name = name
self.left = left
self.right = right
def __str__(self):
return '{}:{}/{}'.format(self.name, self.left, self.right)
root = Node('root')
adding all the code you omitted (more than you supplied!-).
And now, adding your code exactly as reported, the call:
search_bfs(None, root, root)
emits
root:None/None
exactly as desired and contrary to your report.
It follows that your bug is in some of code you didn't show us, not in the coded you did show.
You either have a buggy queue-class, or are building a different tree than you thought, or searching for a node that is not actually in the tree.
Hard to debug code you're now showing, you know.
Added: so now I've integrated the extra code per your edit and at the end I have:
st = searchtree()
st.create('imtheroot')
st.search_bfs(st.root, st.root)
and of course it prints imtheroot as expected.
Is your bug perhaps STILL hiding in parts you're not yet showing, e.g instead of looking for a node you may be looking for something else?
E.g, if the final call was erroneously st.search_bfs(st.root, 'imtheroot') then obviously the search would fail -- you're checking equality of the key parameter with a node, so key clearly must be a node. not a string or other things (unless the Node class defines a very, very peculiar __eq__ method, which the one you've shown fortunately doesn't:-).
I think the issue is that when you do if curr_node == key, curr_node is a Node object, which has an integer .data attribute, but key is the integer value.
So I think you just need to use if curr_node.data == key.
I am reviewing for my final and one of the practice problem asks to implement a function that puts a value into a binary search tree in Python. Here is the Tree implementation I am using.
class Tree(object):
def __init__(self, entry, left=None, right=None):
self.entry = entry
self.left = left
self.right = right
Here is the function I need to fill in.
def insert(item, tree):
"""
>>> t = Tree(5, Tree(1, None, Tree(4)), Tree(7, Tree(6), Tree(8)))
>>> insert(2, t)
>>> t
Tree(5, Tree(1, None, Tree(4, Tree(2), None)), Tree(7, Tree(6), Tree(8)))
"""
Can anyone help me implement this code, as I have no idea where to start? Thanks!
def insert(item, tree):
if (item < tree.entry):
if (tree.left != None):
insert(item, tree.left)
else:
tree.left = Tree(item)
else:
if (tree.right != None):
insert(item, tree.right)
else:
tree.right = Tree(item)
Tree is a Non linear data structure.A tree is created by set of vertices and set of edges.Average searching complexity is logn . Let's consider how to insert values to tree.
First of all , you would create a Vertices.In another way, you would create nodes.then , Those nodes which is created insert hierarchical manner.In creating Node class , You can initialize all the properties of Node class in constructor function.Actually like this,
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
At beginning, Node's data=data, left child of Node is None and right child of Node is None.And then , you can create a binary search tree using those created nodes.
class tree:
def __init__(self):
self.root=None
def insert(self,data):
if(self.root==None):
self.root=Node(data)
else:
self._insert(data,self.root)
def _insert(self, data, curNode):
if(curNode.data>data):
if(curNode.left==None):
curNode.left=Node(data)
else:
self._insert(data,curNode.left)
else:
if(curNode.right==None):
curNode.right=Node(data)
else:
self._insert(data,curNode.right)
At first, root node is initialized under constructor method of tree class.And then insert nodes using insert function.Using any tree traversal method can be printed elements of tree..I think , you could understand.thank you!