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