File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 2 files changed +64
-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+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * class ListNode {
4+ * val: number
5+ * next: ListNode | null
6+ * constructor(val?: number, next?: ListNode | null) {
7+ * this.val = (val===undefined ? 0 : val)
8+ * this.next = (next===undefined ? null : next)
9+ * }
10+ * }
11+ */
12+
13+ function mergeTwoLists ( list1 : ListNode | null , list2 : ListNode | null ) : ListNode | null {
14+ // ๋๋ฏธ ํค๋ ๋
ธ๋๋ฅผ ์์ฑํ์ฌ ๊ฒฐ๊ณผ ๋ฆฌ์คํธ์ ์์์ ์ผ๋ก ์ฌ์ฉ
15+ const dummy = new ListNode ( 0 ) ;
16+ let current = dummy ;
17+
18+ // ๋ ๋ฆฌ์คํธ๋ฅผ ์ํํ๋ฉด์ ๋ ์์ ๊ฐ์ ๊ฐ์ง ๋
ธ๋๋ฅผ ๊ฒฐ๊ณผ ๋ฆฌ์คํธ์ ์ฐ๊ฒฐ
19+ while ( list1 !== null && list2 !== null ) {
20+ if ( list1 . val <= list2 . val ) {
21+ current . next = list1 ;
22+ list1 = list1 . next ;
23+ } else {
24+ current . next = list2 ;
25+ list2 = list2 . next ;
26+ }
27+ current = current . next ;
28+ }
29+
30+ // ๋จ์ ๋
ธ๋๋ค์ ๊ฒฐ๊ณผ ๋ฆฌ์คํธ์ ์ฐ๊ฒฐ
31+ current . next = list1 === null ? list2 : list1 ;
32+
33+ // ๋๋ฏธ ๋
ธ๋์ ๋ค์ ๋
ธ๋๊ฐ ์ค์ ๋ณํฉ๋ ๋ฆฌ์คํธ์ ํค๋
34+ return dummy . next ;
35+ }
You canโt perform that action at this time.
0 commit comments