Code different for Depth and Height - Binary Search Tree (Python) - python

I am confuse, what is the different in code for depth and height in binary search tree?
I did a google to check on the code for depth, as well as the code for height.
It kind of turn out to be the same.
Can someone tell me the differences?
Anyway, below is my code for height as well as depth.
But my depth isn't working.
def height(self,key):
node = self.root
while node is not None:
if node.key == key:
return self.height2(node)
elif node.key > key:
node = node.left
else:
node = node.right
def height2(self,n):
if n is None:
return -1
else:
#return the max
return 1 + max(self.height2(n.left),self.height2(n.right))
For the depth
def depth(self,node):
node = self.root
if node.left == None and node.right == None:
return 1
elif node.left == None:
return node.right.depth() + 1
elif node.right == None:
return node.left.depth() + 1
else:
return 1 + max(self.depth(node.left),self.depth(node.right))
Edited for depth:
def depth(self,key):
temp = self.root
while temp is not None:
if temp.key == key:
return temp.val
elif temp.key > key:
temp = temp.left
else:
temp = temp.right
return return 1 + max(self.depth(node.left),self.depth(node.right))

Depth is a value associated to a single node in a tree, it's the number of edges from a node to root node. Root node has a depth of 0. Height on the other hand is the longest path from a node to root, i.e. max depth of any node in the tree.
The code you have seem to work just fine, height2 is enough to determine the the height of a tree. If you need determine a depth of a node you'd need to first find it.
Assuming the tree is BST then following code would return the depth or -1 if the key is not in the tree:
class Node(object):
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def depth(root, key, current_depth=0):
if not root:
return -1
elif root.key == key:
return current_depth
elif key < root.key:
return depth(root.left, key, current_depth + 1)
else:
return depth(root.right, key, current_depth + 1)
root = Node(3)
root.left = Node(2)
root.left.left = Node(1)
for i in xrange(1, 4):
print 'key: {0}, depth: {1}'.format(i, depth(root, i))
# key: 1, depth: 2
# key: 2, depth: 1
# key: 3, depth: 0

Related

How can I find the depth of a specific node inside a binary tree?

I'm trying to figure out a recursive solution to this problem. The main thing is to return the level in the binary tree where the node is.
def find_depth(tree, node):
if node == None:
return 0
else:
return max(find_depth(tree.left))
#recursive solution here
Using this class for the values:
class Tree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
Example: Calling find_depth(tree, 7) should return the level where 7 is in the tree. (level 2)
3
/ \
7 1 <------ return that 7 is at level 2
/ \
9 3
maybe this is what you are looking for
def find_depth(tree, node):
if node is None or tree is None:
return 0
if tree == node:
return 1
left = find_depth(tree.left, node)
if left != 0:
return 1 + left
right = find_depth(tree.right, node)
if right != 0:
return 1 + right
return 0
You need to provide information about depth in find_depth call. It might look like this (assuming 0 is a sentinel informing that node is not found):
def find_depth(tree, node, depth=1):
if node == None:
return 0
if tree.value == node:
return depth
left_depth = find_depth(tree.left, node, depth+1)
right_depth = find_depth(tree.right, node, depth+1)
return max(left_depth, right_depth)
Then you call it with two parameters: x = find_depth(tree, 7).
Recursion is a functional heritage and so using it with functional style yields the best results -
base case: if the input tree is empty, we cannot search, return None result
inductive, the input tree is not empty. if tree.data matches the search value, return the current depth, d
inductive, the input tree is not empty and tree.data does not match. return the recursive result of tree.left or the recursive result of find.right
def find (t = None, value = None, d = 1):
if not t:
return None # 1
elif t.value == value:
return d # 2
else:
return find(t.left, value, d + 1) or find(t.right, value, d + 1) # 3
class tree:
def __init__(self, value, left = None, right = None):
self.value = value
self.left = left
self.right = right
t = tree \
( 3
, tree(7, tree(9), tree(3))
, tree(1)
)
print(find(t, 7)) # 2
print(find(t, 99)) # None
You can implement the find method in your tree class too
def find (t = None, value = None, d = 1):
# ...
class tree
def __init__ #...
def find(self, value)
return find(self, value)
print(t.find(7)) # 2
print(t.find(99)) # None

Function to create a binary search tree recursively

Picture of Question with specific details
I'm trying to write a function that creates a binary search tree. Here's what I have so far:
def add_items(bst, low, high):
if low == high:
bst.insert(high)
return
else:
left = add_items(bst, low, high)
right = add_items(bst, low, high)
item = BinarySearchTreeMap.Item(low)
node = BinarySearchTreeMap.BinarySearchTreeMap.Node(item)
node.left = left
node.right = right
return node
The problems I noticed with this is that the function returns a node when it finishes all the recursive calls. I want to return the root of this binary search tree, but I'm not sure how to return it at the end. The picture includes a more detailed description of what I am trying to do. I appreciate any help, advice, or ideas anyone may have. add_items is actually sort of a helper function as it is called by this little snippet of code:
def create_complete_bst(n):
bst = BinarySearchTreeMap.BinarySearchTreeMap()
add_items(bst, 1, n)
return bst
P.S. here is the binary search tree class that I have been provided with and am using in this program
class BinarySearchTreeMap:
class Item:
def __init__(self, key, value=None):
self.key = key
self.value = value
class Node:
def __init__(self, item):
self.item = item
self.parent = None
self.left = None
self.right = None
def num_children(self):
count = 0
if (self.left is not None):
count += 1
if (self.right is not None):
count += 1
return count
def disconnect(self):
self.item = None
self.parent = None
self.left = None
self.right = None
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def is_empty(self):
return len(self) == 0
# raises exception if not found
def __getitem__(self, key):
node = self.find(key)
if (node is None):
raise KeyError(str(key) + " not found")
else:
return node.item.value
# returns None if not found
def find(self, key):
curr = self.root
while (curr is not None):
if (curr.item.key == key):
return curr
elif (curr.item.key > key):
curr = curr.left
else: # (curr.item.key < key)
curr = curr.right
return None
# updates value if key already exists
def __setitem__(self, key, value):
node = self.find(key)
if (node is None):
self.insert(key, value)
else:
node.item.value = value
# assumes key not in tree
def insert(self, key, value=None):
item = BinarySearchTreeMap.Item(key, value)
new_node = BinarySearchTreeMap.Node(item)
if (self.is_empty()):
self.root = new_node
self.size = 1
else:
parent = self.root
if(key < self.root.item.key):
curr = self.root.left
else:
curr = self.root.right
while (curr is not None):
parent = curr
if (key < curr.item.key):
curr = curr.left
else:
curr = curr.right
if (key < parent.item.key):
parent.left = new_node
else:
parent.right = new_node
new_node.parent = parent
self.size += 1
# raises exception if key not in tree
def __delitem__(self, key):
node = self.find(key)
if (node is None):
raise KeyError(str(key) + " is not found")
else:
self.delete_node(node)
# assumes key is in tree + returns value assosiated
def delete_node(self, node_to_delete):
item = node_to_delete.item
num_children = node_to_delete.num_children()
if (node_to_delete is self.root):
if (num_children == 0):
self.root = None
node_to_delete.disconnect()
self.size -= 1
elif (num_children == 1):
if (self.root.left is not None):
self.root = self.root.left
else:
self.root = self.root.right
self.root.parent = None
node_to_delete.disconnect()
self.size -= 1
else: #num_children == 2
max_of_left = self.subtree_max(node_to_delete.left)
node_to_delete.item = max_of_left.item
self.delete_node(max_of_left)
else:
if (num_children == 0):
parent = node_to_delete.parent
if (node_to_delete is parent.left):
parent.left = None
else:
parent.right = None
node_to_delete.disconnect()
self.size -= 1
elif (num_children == 1):
parent = node_to_delete.parent
if(node_to_delete.left is not None):
child = node_to_delete.left
else:
child = node_to_delete.right
child.parent = parent
if (node_to_delete is parent.left):
parent.left = child
else:
parent.right = child
node_to_delete.disconnect()
self.size -= 1
else: #num_children == 2
max_of_left = self.subtree_max(node_to_delete.left)
node_to_delete.item = max_of_left.item
self.delete_node(max_of_left)
return item
# assumes non empty subtree
def subtree_max(self, curr_root):
node = curr_root
while (node.right is not None):
node = node.right
return node
def inorder(self):
for node in self.subtree_inorder(self.root):
yield node
def subtree_inorder(self, curr_root):
if(curr_root is None):
pass
else:
yield from self.subtree_inorder(curr_root.left)
yield curr_root
yield from self.subtree_inorder(curr_root.right)
def __iter__(self):
for node in self.inorder():
yield node.item.key
After revising with suggestions:
def create_complete_bst(n):
bst = BinarySearchTreeMap.BinarySearchTreeMap()
add_items(bst, 1, n)
return bst
def add_items(bst, low, high):
if low == high:
bst.insert(high)
return
elif high < low:
return
else:
mid = (low+high) // 2
bst.insert(mid)
add_items(bst, low, mid-1)
add_items(bst, mid+1, high)
return bst

BST height in python

I have written a class called Node with certain functions to create a binary search tree. All of the functions work correctly except the function height() that is supposed to calculate the height of the BST. It returns a very small number compared to what I was expecting it too given that I haven't balanced the tree. The number I was expecting was close to N where N is the amount of numbers I have entered in the tree. Here is the code:
from __future__ import print_function
import random
class Node(object):
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 lookup(self, data, parent=None):
if data < self.data:
if self.left is None:
return None, None
return self.left.lookup(data, self)
elif data > self.data:
if self.right is None:
return None, None
return self.right.lookup(data, self)
else:
return self, parent
def delete(self, data):
node, parent = self.lookup(data)
if node is not None:
children_count = node.children_count()
if children_count == 0:
if parent:
if parent.left is node:
parent.left = None
else:
parent.right = None
else:
self.data = None
elif children_count == 1:
if node.left:
n = node.left
else:
n = node.right
if parent:
if parent.left is node:
parent.left = n
else:
parent.right = n
else:
self.left = n.left
self.right = n.right
self.data = n.data
else:
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 compare_trees(self, node):
if node is None:
return False
if self.data != node.data:
return False
res = True
if self.left is None:
if node.left:
return False
else:
res = self.left.compare_trees(node.left)
if res is False:
return False
if self.right is None:
if node.right:
return False
else:
res = self.right.compare_trees(node.right)
return res
def print_tree(self):
if self.left:
self.left.print_tree()
print(self.data, end=" ")
if self.right:
self.right.print_tree()
def height(self, root):
if root is None:
return 0
else:
return max(self.height(root.left), self.height(root.right)) + 1
random.seed(3)
bst = Node(random.randint(1,1000))
for i in range(1,80000,1):
bst.insert(random.randint(1,1000))
print(bst.height(bst))
You are getting low answer because you are always inserting number from 1 to 1000 only so the numbers existing are always remains same and you are thinking you are inserting 1,80000 numbers but actually because of generating randomly the same numbers from 1 to 1000 you are actually inserting just 1000 values from 1 to 1000 maximum.
Wrong Code
bst = Node(random.randint(1,1000))
for i in range(1,80000,1):
bst.insert(random.randint(1,1000))
print(bst.height(bst))
Modification
bst = Node(random.randint(1,80000))
for i in range(1,80000,1):
bst.insert(random.randint(1,80000))
print(bst.height(bst))
Your code is working fine you can execute below code and check it with the image below
bst = Node(7)
list1 = [3,11,1,5,9,13,4,6,8,12,14,8.5]
for i in list1:
bst.insert(i)
print(bst.height(bst))
bst.print_tree()
Ouput
5
1 3 4 5 6 7 8 8.5 9 11 12 13 14
You should declare as sorted array to get maximum height for binary search tree.
but this may not work for larger numbers as 1000 or 10,000 . It will work fine for 500 elements because of your recursion for insertion may exceed the maximum recursion depth in python
UPTO 500
bst = Node(0)
list1 = list(range(1,500,1))
for i in list1:
bst.insert(i)
print(bst.height(bst))
OUTPUT
499
1000 elements
bst = Node(0)
list1 = list(range(1,500,1))
for i in list1:
bst.insert(i)
print(bst.height(bst))
OUTPUT
self.right.insert(data)
self.right = Node(data)
RecursionError: maximum recursion depth exceeded

Binary Search Tree - finding height and depth

This is my first time coding binary search tree.
I reference alot from online, and tried some of their code.
Was wondering
why this 2 code isn't working and gave me the same error, when I'm trying to print it out
def height(self,node):
if node is None:
return 0
else:
return max(height(node.left), height(node.right)) + 1
def depth(self, count=0):
if self.root is None:
return count
return max(depth(self.root.left, count+1),
depth(self.root.right, count+1))
both have the same error which says
"global name height is not define"
"global name depth is not define"
I wonder why, because I'm calling the same function
complete code:
class BST:
root=None
def put(self, key, val):
self.root = self.put2(self.root, key, val)
def put2(self, node, key, val):
if node is None:
#key is not in tree, create node and return node to parent
return Node(key, val)
if key < node.key:
# key is in left subtree
node.left = self.put2(node.left, key, val)
elif key > node.key:
# key is in right subtree
node.right = self.put2(node.right, key, val)
else:
node.val = val
# node.count = 1 + self.size2(node.left) + self.size2(node.right)
return node
# draw the graph
def drawTree(self, filename):
# create an empty undirected graph
G=pgv.AGraph('graph myGraph {}')
# create queue for breadth first search
q = deque([self.root])
# breadth first search traversal of the tree
while len(q) <> 0:
node = q.popleft()
G.add_node(node, label=node.key+":"+str(node.val))
if node.left is not None:
# draw the left node and edge
G.add_node(node.left, label=node.left.key+":"+str(node.left.val))
G.add_edge(node, node.left)
q.append(node.left)
if node.right is not None:
# draw the right node and edge
G.add_node(node.right, label=node.right.key+":"+str(node.right.val))
G.add_edge(node, node.right)
q.append(node.right)
# render graph into PNG file
G.draw(filename,prog='dot')
os.startfile(filename)
def createTree(self):
self.put("F",6)
self.put("D",4)
self.put("C",3)
self.put("B",2)
self.put("A",1)
self.put("E",5)
self.put("I",9)
self.put("G",7)
self.put("H",8)
self.put("J",10)
def height(self,node):
if node is None:
return 0
else:
return max(height(node.left), height(node.right)) + 1
def depth(self, count=0):
if self.root is None:
return count
return max(depth(self.root.left, count+1),
depth(self.root.right, count+1))
class Node:
left = None
right = None
key = 0
val = 0
def __init__(self, key, val):
self.key = key
self.val = val
bst = BST()
bst.createTree()
bst.drawTree("demo.png")
print bst.get("B")
##print bst.size("D")
##print bst.size("F")
print bst.depth("B")
Python doesn't scope code to the local class automatically :
return max(self.height(node.left), self.height(node.right)) + 1
and
return max(self.depth(self.root.left, count+1),
self.depth(self.root.right, count+1))
Are you sure that your BST.height() and BST.depth() methods are really in the scope of BST? It looks like they are not indented into the BST class. Check your spacing.

how to find the height of a node in binary tree recursively

path = 0 # the lenght of the path
while self.right != None or self.left != None:
while self.right != None:
self = self.right
path = path +1
while self.left != None:
self = self.left
path = path +1
return path
this is my sample code for find the Height, is defined as the length of the
longest path by number of nodes from self to a leaf. The height of a leaf node is 1.
it doesn't work.
What you're doing isn't recursive, it's iterative.
Recursive would be something like:
def height(node):
if node is None:
return 0
else:
return max(height(node.left), height(node.right)) + 1
You were given the solution by mata, but I suggest you also look at your code and understand what it is doing:
while self.right != None:
self = self.right
path = path +1
What will this do? it will find the right child, then its right child, and so on. So this checks only one path of the "rightmost" leaf.
This does the same for the left:
while self.left != None:
self = self.left
path = path +1
The idea in recursion is that for each subproblem, you solve it using the exact same recipe for all other subproblems. So if you would apply your algorithm only to a subtree or a leaf, it would still work.
Also, a recursive definition calls itself (although you can implement this with a loop, but that is beyond the scope here).
Remeber the definition:
Recursion: see definition of Recursion.
;)
def height(node):
if node is None:
return 0
else:
if node.left==None and node.right==None:
return max(height(node.left), height(node.right))+0
else:
return max(height(node.left), height(node.right))+1
If you consider each increasing edge to be the height.
To pass hackerrank testcases
def getHeight(self, root):
if root == None:
return -1
else:
return 1 + max( self.getHeight(root.left), self.getHeight(root.right) )
Here is the complete program in Python ::
class Node :
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def maxDepth(node):
if node is None :
return 0
else :
ldepth = maxDepth(node.left)
rdepth = maxDepth(node.right)
if (ldepth>rdepth):
return ldepth +1
else :
return rdepth +1
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Height of tree is %d" %(maxDepth(root))
Source : here
def height(self):
if self.root !=None:
return self._height(self.root,0)
else:
return 0
def _height(self,cur_node,cur_height):
if cur_node==None :
return cur_height
left_height = self._height(cur_node.left_child,cur_height+1)
right_height = self._height(cur_node.right_child,cur_height+1)
return max(left_height,right_height)

Categories

Resources