Maximum Depth of Binary Tree_DFS

DFS, Stack

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

์ž๋ฃŒ๊ตฌ์กฐ : Stack

์•Œ๊ณ ๋ฆฌ์ฆ˜ 1. ํŠธ๋ฆฌ ๋…ธ๋“œ๋ฅผ ๋ฃจํŠธ์—์„œ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ์Šคํƒ์— ๋„ฃ๋Š”๋‹ค. (๋…ธ๋“œ๋ฅผ ๋„ฃ๋Š” ์Šคํƒ์™€ ๊นŠ์ด ๊ฐ’ ๋„ฃ๋Š” ์Šคํƒ, ๊นŠ์ด ๊ฐ’์€ root=1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค.) 2. pop()ํ•˜๋ฉด์„œ ์™ผ์ชฝ ์ž์‹๊ณผ ์˜ค๋ฅธ์ชฝ ์ž์‹์ด ์žˆ์œผ๋ฉด pushํ•œ๋‹ค. 3. ๋…ธ๋“œ ์Šคํƒ์— ๋…ธ๋“œ๋ฅผ ๋„ฃ์„ ๋•Œ๋งˆ๋‹ค ๊นŠ์ด๊ฐ’์€ +1์”ฉ ์ฆ๊ฐ€ํ•œ๋‹ค. 4. ๊นŠ์ด ๊ฐ’์€ 1->2->3->4.. ์ฆ๊ฐ€ํ•˜๋ฏ€๋กœ Math.max(value, max) ๋กœ ๊นŠ์ด ๊ฐ’์„ ๋น„๊ตํ•˜๋ฉฐ ์ตœ๋Œ“๊ฐ’์„ ๋ฆฌํ„ดํ•œ๋‹ค.

Last updated

Was this helpful?