File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ # RECURSIVE DFS
2+ class Solution :
3+ def maxDepth (self , root : TreeNode ) -> int :
4+ if not root :
5+ return 0
6+
7+ return 1 + max (self .maxDepth (root .left ), self .maxDepth (root .right ))
8+
9+ # ITERATIVE DFS
10+ class Solution :
11+ def maxDepth (self , root : TreeNode ) -> int :
12+ stack = [[root , 1 ]]
13+ res = 0
14+
15+ while stack :
16+ node , depth = stack .pop ()
17+
18+ if node :
19+ res = max (res , depth )
20+ stack .append ([node .left , depth + 1 ])
21+ stack .append ([node .right , depth + 1 ])
22+ return res
23+
24+ # BFS
25+ class Solution :
26+ def maxDepth (self , root : TreeNode ) -> int :
27+ if not root :
28+ return 0
29+
30+ level = 0
31+ q = deque ([root ])
32+ while q :
33+
34+ for i in range (len (q )):
35+ node = q .popleft ()
36+ if node .left :
37+ q .append (node .left )
38+ if node .right :
39+ q .append (node .right )
40+ level += 1
41+ return level
You can’t perform that action at this time.
0 commit comments