the art of
Algorithm
Notes on Analysis and Design



Max Depth of a tree

Compute the “maxDepth” of a tree – the number of nodes along the longest path from the root node down to the farthest leaf node

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#A binary tree node
class Node:
  #Constructor to create new node
	def __init__(self,key):
		self.left=None
		self.right=None
		self.data=key
#Function to compute maxdepth of tree
def maxdepth(node):
	if node is None:
		return 0
	else:
		ldepth=maxdepth(node.left)
		rdepth=maxdepth(node.right)
		return max(ldepth+1,rdepth+1)
#Main Program to compute above function
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))