File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * ๋ฌธ์ ์์ฝ: ์ด์ง ํธ๋ฆฌ์ ๋ฃจํธ ๋
ธ๋๊ฐ ์ฃผ์ด์ง ๋, ์ด ํธ๋ฆฌ์ ์ต๋ ๊น์ด๋ฅผ ๋ฐํํด์ผ ํ๋ค
3
+ * ์ต๋ ๊น์ด: ๋ฃจํธ ๋
ธ๋์์ ๊ฐ์ฅ ๋จผ ๋ฆฌํ ๋
ธ๋๊น์ง์ ๊ฒฝ๋ก์ ์๋ ๋
ธ๋์ ์
4
+ * ์๊ฐ ๋ณต์ก๋: O(n) - ๋ชจ๋ ๋
ธ๋๋ฅผ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธ
5
+ * ๊ณต๊ฐ ๋ณต์ก๋: O(h) - h๋ ํธ๋ฆฌ์ ๋์ด(์ต์
์ ๊ฒฝ์ฐ O(n)) - ์ฌ๊ท ํธ์ถ ์คํ ์ฌ์ฉ
6
+ */
7
+
8
+ /**
9
+ * Definition for a binary tree node.
10
+ * function TreeNode(val, left, right) {
11
+ * this.val = (val===undefined ? 0 : val)
12
+ * this.left = (left===undefined ? null : left)
13
+ * this.right = (right===undefined ? null : right)
14
+ * }
15
+ */
16
+ /**
17
+ * @param {TreeNode } root
18
+ * @return {number }
19
+ */
20
+ var maxDepth = function ( root ) {
21
+ // ๊ธฐ์ ์กฐ๊ฑด: ๋
ธ๋๊ฐ ์์ผ๋ฉด(empty tree) ๊น์ด๋ 0
22
+ if ( root === null ) {
23
+ return 0 ;
24
+ }
25
+
26
+ const leftDepth = maxDepth ( root . left ) ;
27
+ const rightDepth = maxDepth ( root . right ) ;
28
+
29
+ // ํ์ฌ ๋
ธ๋์ ์ต๋ ๊น์ด: ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ์ ์ต๋ ๊น์ด ์ค ํฐ ๊ฐ์ 1์ ๋ํ ๊ฐ
30
+ return Math . max ( leftDepth , rightDepth ) + 1 ;
31
+ } ;
You canโt perform that action at this time.
0 commit comments