File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ ๋ฌธ์ : ์ด์ง ํธ๋ฆฌ์ ์ต๋ ๊น์ด๋ฅผ ๊ตฌํ์์ค.
3+ ํ์ด: ๊น์ด ์ฐ์ ํ์(DFS)์ ์ฌ์ฉํ์ฌ ํธ๋ฆฌ์ ๊ฐ ๊ฒฝ๋ก๋ฅผ ํ์ํ๊ณ , ์ต๋ ๊น์ด๋ฅผ ๊ฐฑ์ ํฉ๋๋ค.
4+ ์๊ฐ ๋ณต์ก๋: O(n), n์ ํธ๋ฆฌ์ ๋
ธ๋ ์์
๋๋ค. ๋ชจ๋ ๋
ธ๋๋ฅผ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธํ๋ฏ๋ก ์ ์ฒด ์๊ฐ ๋ณต์ก๋๋ O(n)์
๋๋ค.
5+ ๊ณต๊ฐ ๋ณต์ก๋: O(h), h๋ ํธ๋ฆฌ์ ๋์ด์
๋๋ค. ์ฌ๊ท ํธ์ถ ์คํ์ด ์ต๋ h ๊น์ด๊น์ง ์์ผ ์ ์์ผ๋ฏ๋ก ๊ณต๊ฐ ๋ณต์ก๋๋ O(h)์
๋๋ค.
6+ ์ฌ์ฉํ ์๋ฃ๊ตฌ์กฐ: ํจ์(์ฌ๊ท ํธ์ถ ์คํ)
7+ '''
8+
9+
10+ # Definition for a binary tree node.
11+ # class TreeNode:
12+ # def __init__(self, val=0, left=None, right=None):
13+ # self.val = val
14+ # self.left = left
15+ # self.right = right
16+ class Solution :
17+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
18+ if not root :
19+ return 0
20+ answ = 1
21+ def dfs (root , a ):
22+ nonlocal answ
23+ if root .left :
24+ dfs (root .left , a + 1 )
25+ if root .right :
26+ dfs (root .right , a + 1 )
27+ answ = max (answ , a )
28+ return a
29+ dfs (root , 1 )
30+ return answ
31+
32+
You canโt perform that action at this time.
0 commit comments