File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 )
You can’t perform that action at this time.
0 commit comments