File tree Expand file tree Collapse file tree
maximum-depth-of-binary-tree Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * ์ด์ง ํธ๋ฆฌ์ ์ต๋ ๊น์ด๋ฅผ ์ฌ๊ท์ ์ผ๋ก ๊ณ์ฐ (DFS)
3+ *
4+ * ์๊ฐ ๋ณต์ก๋: O(n), n์ ํธ๋ฆฌ์ ๋
ธ๋ ์
5+ * ๊ณต๊ฐ ๋ณต์ก๋: O(h), h๋ ํธ๋ฆฌ์ ๋์ด, ์ฌ๊ท ํธ์ถ๋ก ์ธํด ์คํ์ ์์ด๋ ํจ์ ํธ์ถ์ ๊น์ด ๋๋ฌธ
6+ */
7+ class Solution {
8+ public int maxDepth (TreeNode root ) {
9+ if (root == null ) {
10+ return 0 ;
11+ }
12+
13+ int leftDepth = maxDepth (root .left );
14+ int rightDepth = maxDepth (root .right );
15+
16+ return Math .max (leftDepth , rightDepth ) + 1 ;
17+ }
18+ }
19+
20+ /**
21+ * ์ด์ง ํธ๋ฆฌ์ ์ต๋ ๊น์ด๋ฅผ ๋ฐ๋ณต์ ์ผ๋ก ๊ณ์ฐ (BFS)
22+ *
23+ * ์๊ฐ ๋ณต์ก๋: O(n), n์ ํธ๋ฆฌ์ ๋
ธ๋ ์
24+ * ๊ณต๊ฐ ๋ณต์ก๋: O(n), ํ์ ์ ์ฅ๋๋ ๋
ธ๋ ์ ๋๋ฌธ
25+ */
26+ class Solution {
27+ public int maxDepth (TreeNode root ) {
28+ if (root == null ) {
29+ return 0 ;
30+ }
31+
32+ Queue <TreeNode > queue = new LinkedList <>();
33+ queue .offer (root );
34+
35+ int depth = 0 ;
36+
37+ while (!queue .isEmpty ()) {
38+ int size = queue .size ();
39+
40+ for (int i = 0 ; i < size ; i ++) {
41+ TreeNode current = queue .poll ();
42+
43+ if (current .left != null ) {
44+ queue .offer (current .left );
45+ }
46+
47+ if (current .right != null ) {
48+ queue .offer (current .right );
49+ }
50+ }
51+
52+ depth ++;
53+ }
54+
55+ return depth ;
56+ }
57+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * ์ฌ๊ท๋ฅผ ์ฌ์ฉํ์ฌ ๋ ๊ฐ์ ์ ๋ ฌ๋ ์ฐ๊ฒฐ ๋ฆฌ์คํธ๋ฅผ ๋ณํฉ
3+ *
4+ * ์๊ฐ ๋ณต์ก๋: O(n + m), n์ list1์ ๊ธธ์ด, m์ list2์ ๊ธธ์ด
5+ * ๊ณต๊ฐ ๋ณต์ก๋: O(n + m), ์ฌ๊ท ํธ์ถ๋ก ์ธํด ์คํ์ ์์ด๋ ํจ์ ํธ์ถ์ ๊น์ด ๋๋ฌธ
6+ */
7+ class Solution {
8+ public ListNode mergeTwoLists (ListNode list1 , ListNode list2 ) {
9+ if (list1 == null ) return list2 ;
10+ if (list2 == null ) return list1 ;
11+
12+ if (list1 .val <= list2 .val ) {
13+ list1 .next = mergeTwoLists (list1 .next , list2 );
14+ return list1 ;
15+ } else {
16+ list2 .next = mergeTwoLists (list1 , list2 .next );
17+ return list2 ;
18+ }
19+ }
20+ }
You canโt perform that action at this time.
0 commit comments