Skip to content

Commit dc54380

Browse files
committed
Merge pull request mission-peace#105 from orsenthil/skumaran/python/max_depth_binary_tree
Max Depth Binary Tree.
2 parents 4bf7c6b + 4c2779a commit dc54380

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
Problem Statement
3+
=================
4+
5+
Given a binary tree, write a program to find the maximum depth at any given node.
6+
7+
For e.g, for this binary tree.
8+
9+
1
10+
/ \
11+
2 3
12+
/ \
13+
4 5
14+
15+
The height at 1 is 3, and the height at 3 is 2.
16+
17+
"""
18+
19+
class Node:
20+
def __init__(self, value):
21+
self.value = value
22+
self.left = None
23+
self.right = None
24+
25+
26+
n1 = Node(1)
27+
n2 = Node(2)
28+
n3 = Node(3)
29+
n4 = Node(4)
30+
n5 = Node(5)
31+
32+
# construct the tree as given in the problem.
33+
34+
n1.left = n2
35+
n1.right = n3
36+
n3.left = n4
37+
n3.right = n5
38+
39+
40+
def find_max_depth(n):
41+
if n is None:
42+
return 0
43+
left_height = find_max_depth(n.left)
44+
right_height = find_max_depth(n.right)
45+
if left_height > right_height:
46+
result = left_height + 1
47+
else:
48+
result = right_height + 1
49+
return result
50+
51+
52+
if __name__ == '__main__':
53+
assert 3 == find_max_depth(n1)
54+
assert 2 == find_max_depth(n3)

0 commit comments

Comments
 (0)