File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ from collections import deque
2
+
3
+ # Definition for a binary tree node.
4
+ # class TreeNode:
5
+ # def __init__(self, val=0, left=None, right=None):
6
+ # self.val = val
7
+ # self.left = left
8
+ # self.right = right
9
+ class Solution :
10
+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
11
+ if not root :
12
+ return 0
13
+
14
+ def bfs (n ):
15
+ queue = deque ([n ])
16
+ depth = 0
17
+
18
+ while queue :
19
+ depth += 1
20
+ for _ in range (len (queue )):
21
+ node = queue .popleft ()
22
+ if node .left :
23
+ queue .append (node .left )
24
+ if node .right :
25
+ queue .append (node .right )
26
+ return depth
27
+
28
+ def dfs (n ):
29
+ stack = [n ]
30
+ max_depth = 0
31
+ visited = {n : 1 }
32
+
33
+ while stack :
34
+ node = stack .pop ()
35
+ depth = visited [node ]
36
+ max_depth = max (max_depth , depth )
37
+ if node .left :
38
+ visited [node .left ] = depth + 1
39
+ stack .append (node .left )
40
+ if node .right :
41
+ visited [node .right ] = depth + 1
42
+ stack .append (node .right )
43
+ return max_depth
44
+
45
+ return dfs (root )
46
+
47
+
48
+ """
49
+ bfs 방식으로 left나 right가 있으면 스택에 넣고 depth + 1, dfs보다 비효율인 듯
50
+ """
You can’t perform that action at this time.
0 commit comments