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
+ * Definition for a binary tree node.
3
+ * function TreeNode(val, left, right) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.left = (left===undefined ? null : left)
6
+ * this.right = (right===undefined ? null : right)
7
+ * }
8
+ */
9
+ /**
10
+ * @param {TreeNode } root
11
+ * @return {number }
12
+ */
13
+ var maxDepth = function ( root ) {
14
+ if ( ! root ) return 0 ; // ๋
ธ๋๊ฐ ์์ผ๋ฉด ๊น์ด๋ 0
15
+
16
+ // ํ์ฌ ๋
ธ๋๊ฐ ์กด์ฌํ๋ฏ๋ก ๊ธฐ๋ณธ ๊น์ด๋ 1
17
+ // ์์์ด ์์ ์๋ ๊ฒฝ์ฐ๋ฅผ ๋๋นํด ์ด๊ธฐ๊ฐ ์ค์
18
+ let left = 1 ;
19
+ let right = 1 ;
20
+
21
+ // ์ผ์ชฝ ์๋ธํธ๋ฆฌ๊ฐ ์์ผ๋ฉด ์ฌ๊ท์ ์ผ๋ก ๊น์ด ๊ณ์ฐ ํ ํ์ฌ ๋ ๋ฒจ(+1) ์ถ๊ฐ
22
+ if ( root . left ) {
23
+ left = maxDepth ( root . left ) + 1 ;
24
+ }
25
+ // ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๊ฐ ์์ผ๋ฉด ์ฌ๊ท์ ์ผ๋ก ๊น์ด ๊ณ์ฐ ํ ํ์ฌ ๋ ๋ฒจ(+1) ์ถ๊ฐ
26
+ if ( root . right ) {
27
+ right = maxDepth ( root . right ) + 1 ;
28
+ }
29
+ // ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ ์ค ๋ ๊น์ ๊ฐ์ ๋ฐํ
30
+ return Math . max ( left , right ) ;
31
+ } ;
You canโt perform that action at this time.
0 commit comments