I build a binary tree with python code, now I could print it in order with testTree.printInorder(testTree.root). I have tried to lookup some node ,and the function findNode doesn't work anymore . print testTree.findNode(testTree.root,20) whatever I put in just return None.
class TreeNode:
def __init__(self, value):
self.left = None;
self.right = None;
self.data = value;
class Tree:
def __init__(self):
self.root = None
def addNode(self,node,value):
if node == None:
self.root = TreeNode(value)
else:
if value < node.data:
if node.left == None:
node.left = TreeNode(value)
else:
self.addNode(node.left,value)
else:
if node.right == None:
node.right = TreeNode(value)
else:
self.addNode(node.right,value)
def printInorder(self,node):
if node != None:
self.printInorder(node.left)
print node.data
self.printInorder(node.right)
def findNode(self,node,value):
if self.root != None:
if value == node.data:
return node.data
elif value < node.data and node.left != None:
self.findNode(node.left,value)
elif value > node.data and node.right != None:
self.findNode(node.right,value)
else:
return None
testTree = Tree()
testTree.addNode(testTree.root, 200)
testTree.addNode(testTree.root, 300)
testTree.addNode(testTree.root, 100)
testTree.addNode(testTree.root, 30)
testTree.addNode(testTree.root, 20)
#testTree.printInorder(testTree.root)
print testTree.findNode(testTree.root,20)
Any function without an explicit return will return None.
You have not returned the recursive calls within findNode. So, here.
if value == node.data:
return node.data
elif value < node.data and node.left != None:
return self.findNode(node.left,value)
elif value > node.data and node.right != None:
return self.findNode(node.right,value)
Now, I can't help but thinking this is a bit noisy. You'll always start adding from the root, yes?
testTree.addNode(testTree.root, 200)
You could rather do this
testTree.addNode(200)
And to do that, you basically implement your methods on the TreeNode class instead. So, for the addNode.
You could also "return up" from the recursion, rather than "pass down" the nodes as parameters.
class TreeNode:
def __init__(self, value):
self.left = None
self.right = None
self.data = value
def addNode(self,value):
if self.data == None: # Ideally, should never end-up here
self.data = value
else:
if value < self.data:
if self.left == None:
self.left = TreeNode(value)
else:
self.left = self.left.addNode(value)
else:
if self.right == None:
self.right = TreeNode(value)
else:
self.right = self.right.addNode(value)
return self # Return back up the recursion
Then, in the Tree class, just delegate the addNode responsibility to the root
class Tree:
def __init__(self):
self.root = None
def addNode(self,value):
if self.root == None:
self.root = TreeNode(value)
else:
self.root = self.root.addNode(value)
When you recurse to children in findNode you need to return the result, otherwise the function will implicitly return None:
def findNode(self,node,value):
if self.root != None:
if value == node.data:
return node.data
elif value < node.data and node.left != None:
return self.findNode(node.left,value) # Added return
elif value > node.data and node.right != None:
return self.findNode(node.right,value) # Added return
else:
return None
Related
I have problem with infinite loop in getMinimal() method. It works in this way :
1)Take node,
2)If node has other node on the left - go to other one.
3)Repeat as far as node has sth on the left side
4)Return the minimal node.
But sometimes it works in infinite loop for example from 1000 to 400, then to 4 then..to 1000! I have no ide where I make mistake. I reviewed this code many times,every single "pointer" to parent/left/right node is okay! Please - help.
Algorithm works okay to "handwritten" trees - ~20nodes. I wanted to test it in better cases - 2500nodes,generated by random lib (from -10k to 10k).
import random
class Node:
def __init__(self, val):
self.val = val
self.parent = None
self.right = None
self.left = None
# Class of node.
def str(self):
return str(self.val)
class MyTree:
def __init__(self, node):
self.root = node
def insert(self, node):
current = self.root
a = True
while a:
if node.val > current.val:
if current.right is not None:
current = current.right
continue
else:
current.right = node
node.parent = current
a = False
if node.val <= current.val:
if current.left is not None:
current = current.left
continue
else:
current.left = node
node.parent = current
a = False
def search(self, node):
current = self.root
while node.val != current.val:
if node.val > current.val:
current = current.right
continue
elif node.val <= current.val:
current = current.left
continue
if node.val == current.val:
return current
else:
print("There is no such node!")
def delete(self, node):
if isinstance(node, (float, int)):
node = self.search(node)
if node is self.root:
self.__deleteRoot()
return
else:
if node.right is None and node.left is None:
self.__deleteNN(node)
return
if node.right is None and node.left is not None:
self.__deleteLN(node)
return
if node.right is not None and node.left is None:
self.__deleteNR(node)
return
if node.right is not None and node.left is not None:
self.__deleteLR(node)
return
def __deleteNN(self, node):
if node.parent.left is node:
node.parent.left = None
if node.parent.right is node:
node.parent.right = None
def __deleteLN(self, node):
parent = node.parent
son = node.left
# parent replaced
if parent.left is node:
parent.left = son
if parent.right is node:
parent.right = son
son.parent = parent
def __deleteNR(self,node):
parent = node.parent
son = node.right
# replace parent
if parent.left is node:
parent.left = son
if parent.right is node:
parent.right = son
son.parent = parent
def __deleteLR(self, node):
minimal = self.getMinimal(node.right)
if minimal.parent.left is minimal:
minimal.parent.left = None
if minimal.parent.right is minimal:
minimal.parent.right = None
# parent of minimal done..
if node.parent.left is node:
node.parent.left = minimal
if node.parent.right is node:
node.parent.right = minimal
minimal.right = node.right
minimal.left = node.left
def getMinimal(self, node):
k = node
while k.left is not None:
k = k.left
return k
def getMax(self):
current = self.root
while current.right:
current = current.right
return current
def __trav(self, node):
if not node:
return
print(node.val)
self.__trav(node.left)
self.__trav(node.right)
def printTrav(self):
self.__trav(self.root)
def __deleteRoot(self):
if self.root.left is None and self.root.right is None:
self.root = None
return
if self.root.left is None and self.root.right is not None:
# left empty,right full
self.root.right.parent = None
self.root = self.root.right
return
if self.root.left is not None and self.root.right is None:
# right empty, left full
self.root.left.parent = None
self.root = self.root.left
return
# node has both children
if self.root.left is not None and self.root.right is not None:
temp = self.getMinimal(self.root.right) # minimal from right subtree
# sometimes it could be like this..
# r
# \
# x
if temp.parent.left is temp:
temp.parent.left = None
else:
temp.parent.right = None
self.root.left.parent = temp
self.root.right.parent = temp
temp.right = self.root.right
temp.left = self.root.left
self.root = temp
self.root.parent = None
return
def search(self, val):
node = self.root
if node.val == val:
return node
if val > node.val and node.right is not None:
node = node.right
if val < node.val and node.left is not None:
node = node.left
else:
print("There's no such value!")
return
def printMax(self):
print(self.getMax().val)
def printMin(self):
print(self.getMinimal(self.root).val)
arr=[None]*2500
for x in range(2500):
arr[x]=Node(random.randint(-10000,10000))
myTree = MyTree(arr[0])
for x in range(1,2500):
myTree.insert(arr[x])
for x in range(2500):
myTree.delete(arr[x])
It is suspicious that you define search twice.
Still that said, here is how I would debug this. I would modify your program to read from a file, try to run, and then detect an endless loop and bail out. Now write random files until you have one that causes you to crash.
Once you have a random file that shows the bug, the next step is to make it minimal. Here is a harness that can let you do that.
import itertools
flatten = itertools.chain.from_iterable
# bug_found should be a function that takes a list of elements and runs your test.
# example should be an array that demonstrates the bug.
def find_minimal (bug_found, example):
parts = [example]
while 1 < max(len(part) for part in parts):
i = 0
while i < len(parts):
if 1 == len(parts[i]):
i = i + 1
else:
part = parts.pop(i)
# Divide in 2.
mid = len(part)/2
part1 = part[0:mid]
part2 = part[mid:len(part)]
# Do we need part1?
parts.insert(i, part1)
if bug_found(flatten(parts)):
i = i + 1
parts.insert(i, part2)
else:
parts[i] = part2
# Do we need part2?
if bug_found_func(flatten(parts)):
i = i + 1
else:
parts.pop(i)
return list(flatten(parts))
Just let it run, and after some time it is likely to find a small example. Which will greatly aid in debugging.
So - I found 2 serious bugs in code. Both in LR ("standard" node and root). As I suspected - bugs were in pointers. Now tree is working (tested few times for 20k,30k and 100k nodes). Solved.
I know that I need an instance of TernaryTree() to be initially be empty until it is by the generate_tree() method using values in list L. Tried a variety of methods but not sure where to go from here. What do I need to add to get value to pass through?
class TernaryTree(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.mid = None
def insert_node(self, new_value):
if new_value <= self.value: #check if value is lower
if self.left == None: #if value is none
self.left = TernaryTree(new_value) #add in node value
else:
self.left.insert_node(new_value) #go left place node value
elif new_value == self.value: #check if value is the same
if self.mid == None:
self.mid = TernaryTree(new_value)
else:
self.mid.insert_node(new_value)
else: #case when new_value > self.value:
if self.right == None:
self.right = TernaryTree(new_value)
else:
self.right.insert_node(new_value)
def traverse_LMRW(self):
if self.left != None: #alternatively, if self.left:
self.left.traverse_LMRW() #go a level deeper
if self.mid != None:
self.mid.traverse_LMRW()
if self.right != None: #if node on right is not None!
self.right.traverse_LMRW() #go a level deeper
print(self.value)
def leaf_count(self):
if self is None:
return 0
if(self.left is None and self.right is None):
return 1
else:
return leaf_count(self.left) + leaf_count(self.right)
def generate_tree(L):
T = TernaryTree(L[0]) #first element in our list is the root by default
for value in L[1:]:
T.insert_node(value)
return T
def main():
L = [4,1,2,2,3,1,0,4,6,5,6,4]
T = TernaryTree()
T.generate_tree(L)
T.traverse_LMRW()
T.leaf_count()
main()
As per your code generate_tree is not a instance method. So indent out it from class indentation. And call it as python function from there it will create instance of TernaryTree.
In main you were creating instance of TernaryTree without any initial value which is required in __init__ constructor.
Update code will be:
class TernaryTree(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.mid = None
def insert_node(self, new_value):
if new_value <= self.value: #check if value is lower
if self.left == None: #if value is none
self.left = TernaryTree(new_value) #add in node value
else:
self.left.insert_node(new_value) #go left place node value
elif new_value == self.value: #check if value is the same
if self.mid == None:
self.mid = TernaryTree(new_value)
else:
self.mid.insert_node(new_value)
else: #case when new_value > self.value:
if self.right == None:
self.right = TernaryTree(new_value)
else:
self.right.insert_node(new_value)
def traverse_LMRW(self):
if self.left != None: #alternatively, if self.left:
self.left.traverse_LMRW() #go a level deeper
if self.mid != None:
self.mid.traverse_LMRW()
if self.right != None: #if node on right is not None!
self.right.traverse_LMRW() #go a level deeper
print(self.value)
def leaf_count(self):
if self is None:
return 0
if(self.left is None and self.right is None):
return 1
else:
return leaf_count(self.left) + leaf_count(self.right)
def generate_tree(L):
T = TernaryTree(L[0]) #first element in our list is the root by default
for value in L[1:]:
T.insert_node(value)
return T
def main():
L = [4,1,2,2,3,1,0,4,6,5,6,4]
T = generate_tree(L)
T.traverse_LMRW()
T.leaf_count()
main()
You're receiving this error because you did not pass a value to your TernaryTree constructor. I guess here generate_tree as a classmethod is what you really need.
I am finished with the case when the node that i want to remove is the root node or the leaf node, but i need to be able to remove also when it has siblings or children, which i am finding very hard.
class Node:
def __init__(self, key=None, data=None):
self.key = key
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
self.size = 0
def remove(self, key):
self.root = self._remove(key, self.root)
def insert(self, key, data):
self.root = self._insert(self.root, key, data)
def _insert(self, root, key, data):
if root == None:
self.size += 1
return Node(key, data)
if root.key == key:
return root
elif root.key > key:
root.left = self._insert(root.left, key, data)
else:
root.right = self._insert(root.right, key, data)
return root
def _remove(self, key, node):
if node == None:
return None
if key == node.key:
if node.left != None and node.right == None: # if trying to remove root and right side is empty
return node.left
elif node.left == None and node.right != None: # if trying to remove root and left side is empty
return node.right
elif node.left == None and node.right == None: # if trying to remove leaf
return node
# two more cases to check when it has siblings
# iterates recursively in the bst
elif key <= node.key:
node.left = self._remove(key, node.left)
else:
node.right = self._remove(key, node.right)
return node
I posted the whole code so if anyone wants to test in their machine is welcome to do so, or someone can use it for educational purpose.
In the future try to perform some debugging and provide some sample output and expected output.
Consider below
def _remove(self, key, node):
if node == None:
return None
if key == node.key:
if node.left and not node.right: # only left
return node.left
elif node.right and not node.left: # only right
return node.right
elif not node.right and not node.left: # neither
return None
else : # both
inorder_successor = node.right
while inorder_successor.left:
inorder_successor = inorder_successor.left
# remember to replace inorder_successor with it's right child
...
...
return inorder_successor
# iterates recursively in the bst
elif key <= node.key:
node.left = self._remove(key, node.left)
else:
node.right = self._remove(key, node.right)
return node
A few observations about what changed
You check for None using, is != None which is a very non Pythonic way to it. Just check for is and is not instead
The right way to replace a node in a BST that has both children is with the inorder successor (left most descendant of the right child of the deleted node)
This error is occurring when we call the lookup method. Can anyone say how can it be rectified? I am unable to debug it using the available documents online. This is an implementation of a binary tree class. I know it is something related to the equivalence problem.
import deque
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
else:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
def lookup(self, data, parent=None):
if self.data == data:
return self, parent
if data < self.data:
if self.left is None:
return None
else:
return self.left.lookup(data, parent=self)
else:
if self.right is None:
return None
else:
return self.right.lookup(data, parent=self)
# aka bfs traversal
def level_traversal(self):
root = self
dq = deque()
dq.append(root)
while dq:
root = dq.popleft()
if root.left:
dq.append(root.left)
if root.right:
dq.append(root.right)
print (root.data)
def delete(self, data):
node, parent = self.lookup(data)
if node.children_count() == 0:
if parent.left == node:
parent.left = None
else:
parent.right = None
del node
elif node.children_count() == 1:
if node.left:
n = node.left
else:
n = node.right
if parent:
if parent.left == node:
parent.left = n
else:
parent.right = n
del node
else:
# find the successor
parent = node
successor = node.right
while successor.left:
parent = successor
successor = successor.left
node.data = successor.data
if parent.left == successor:
parent.left = successor.right
else:
parent.right = successor.right
def inorder(self):
if self.left:
self.left.inorder()
print (self.data)
if self.right:
self.right.inorder()
def preorder(self):
print (self.data)
if self.left:
self.left.preorder()
if self.right:
self.right.preorder()
def postorder(self):
if self.left:
self.left.postorder()
if self.right:
self.right.postorder()
print (self.data)
root = Node(8)
root.insert(3)
root.insert(10)
root.insert(1)
root.insert(6)
root.insert(4)
root.insert(7)
root.insert(14)
root.insert(13)
# look up
print (root.lookup(6))
# level traversal
root.level_traversal()
#mirror image
#root.mirror_image()
#root.delete(3)
#root.level_traversal()
# inorder
#root.inorder()
# pre order
#root.preorder()
# postorder
#root.postorder()
# size
#root.size()
#root.dfs()
#print root.height()
This is not an error at all. This happens because you are returning a tuple of objects from your lookup method, and this is just how objects are represented when you print them out. If you don't like this, you can overwrite the __repr__() method.
Try this in your class definition.
Definition for a binary Tree Node
class TreeNode:
def __init__(self, val = 0, left = None, right = None):
self.val = val
self.left = left
self.right = right
## print TreeNode Object
def __repr__(self) -> str:
return '[%s, %r, %r]' % (self.val, self.left, self.right)
I am trying to practice BST tree implementation with python, following is my code,
import pdb
class Node():
def __init__(self, parent=None, key=None):
self.parent = parent if parent != None else None
self.left = None
self.right = None
self.key = key if key != None else None
class BST():
def __init__(self):
self.root = Node()
def insertKey (self, key):
#pdb.set_trace()
# transverse till we find empty position
if (self.root.key == None):
self.root.key = key
else:
node = self.root
while (node.left != None and node.right != None):
if node.key < key:
node = node.right
else:
node = node.left
#we have node either left or right is empty
if node.key < key:
node.right = Node (node, key)
else:
node.left = Node (node, key)
def inOrder (self, node):
#pdb.set_trace()
if node != None:
self.inOrder (node.left)
print node.key
self.inOrder (node.right)
def printLeft (self, node):
if node != None:
self.printLeft (node)
print node.key
def debugAll (self):
self.inOrder (self.root)
#self.printLeft (self.root)
def fromArray (self, numbers):
srt = sorted(numbers)
print srt
length = len(srt)
mid = length/2
rootEle = srt[mid]
self.insertKey (rootEle)
for i in range (1, mid+1):
try:
#pdb.set_trace()
self.insertKey (srt[mid-i])
self.insertKey (srt[mid+i])
except IndexError:
pass
bst = BST()
bst.fromArray ([1,2,4,3,6,5,10,8,9])
bst.debugAll ()
However the result of the inOrder tree walk is unexpected
1
4
5
6
10
I tried to debug through the pdb while inserting the keys, the keys are properly inserted, but when transversing the tree, some Node are skipped because they're marked as 'NoneType'. May be I am missing out on some language specifics here.
For a start, the code you have below isn't right:
while (node.left != None and node.right != None):
if node.key < key:
node = node.right
else:
node = node.left
It will stop descending if either the left or the right node doesn't exist.
EDIT: If you modify the loop like this, it works. Could be better optimized, but it's a start...
class Node():
def __init__(self, parent=None, key=None):
self.parent = parent if parent != None else None
self.left = None
self.right = None
self.key = key if key != None else None
class BST():
def __init__(self):
self.root = Node()
def insertKey (self, key):
#pdb.set_trace()
# transverse till we find empty position
if (self.root.key == None):
self.root.key = key
else:
node = self.root
while 1:
if node.key < key:
if node.right is None:
node.right = Node(node, key)
break
else:
node = node.right
else:
if node.left is None:
node.left = Node(node, key)
break
else:
node = node.left
def inOrder (self, node):
#pdb.set_trace()
if node != None:
self.inOrder (node.left)
print node.key
self.inOrder (node.right)
def printLeft (self, node):
if node != None:
self.printLeft (node)
print node.key
def debugAll (self):
self.inOrder (self.root)
#self.printLeft (self.root)
def fromArray (self, numbers):
srt = sorted(numbers)
print srt
length = len(srt)
mid = length/2
rootEle = srt[mid]
self.insertKey (rootEle)
for i in range (1, mid+1):
try:
#pdb.set_trace()
self.insertKey (srt[mid-i])
self.insertKey (srt[mid+i])
except IndexError:
pass
bst = BST()
bst.fromArray ([1,2,4,3,6,5,10,8,9])
bst.debugAll ()