Skip to content

Commit 069e5e0

Browse files
authored
Merge pull request #1814 from mkwkw/main
[mkwkw] WEEK 04 Solutions
2 parents 87d975c + 2323d4d commit 069e5e0

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
int maxDepth(TreeNode* root) {
15+
16+
//root가 비어있는 경우
17+
if(root == nullptr)
18+
{
19+
return 0;
20+
}
21+
22+
stack<TreeNode*> nodeStack;
23+
stack<int> depthStack;
24+
int maxDepth = 0;
25+
26+
nodeStack.push(root);
27+
depthStack.push(1);
28+
29+
while(!nodeStack.empty())
30+
{
31+
TreeNode* rootNode = nodeStack.top(); //change root pointer
32+
int rootDepth = depthStack.top();
33+
maxDepth = max(maxDepth, rootDepth);
34+
nodeStack.pop();
35+
depthStack.pop();
36+
37+
//making max depth binary tree
38+
if(rootNode->left != nullptr)
39+
{
40+
nodeStack.push(rootNode->left);
41+
depthStack.push(rootDepth+1);
42+
}
43+
44+
if(rootNode->right != nullptr)
45+
{
46+
nodeStack.push(rootNode->right);
47+
depthStack.push(rootDepth+1);
48+
}
49+
50+
}
51+
return maxDepth;
52+
}
53+
};

merge-two-sorted-lists/mkwkw.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
//풀이 참고하였음.
12+
class Solution {
13+
public:
14+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { //list1, list2 다 포인터
15+
ListNode mergedNode(-1); //mergedNode 객체 선언
16+
ListNode* mergedNodeList = &mergedNode; //node: (merged 객체)의 (주소) (&merged)저장 (객체를 포인터에 넣기)
17+
18+
ListNode* l1 = list1; // 포인터 l1
19+
ListNode* l2 = list2; // 포인터 l2
20+
21+
while (l1 != nullptr && l2 != nullptr) {
22+
//l1, l2 둘 중에 head 값(->val) 값이 작은 것을 node->next에 연결
23+
if (l1->val < l2->val) { // 포인터로 객체의 속성 참조(->)
24+
mergedNodeList->next = l1;
25+
l1 = l1->next;
26+
} else {
27+
mergedNodeList->next = l2;
28+
l2 = l2->next;
29+
}
30+
mergedNodeList = mergedNodeList->next;
31+
}
32+
33+
//남아있는 list를 node->next에 연결
34+
mergedNodeList->next = (l1 != nullptr) ? l1 : l2;
35+
//return the head of the merged linked list (mergeNode -1 다음 것을 가리키는 포인터 next)
36+
return mergedNode.next;
37+
38+
}
39+
};

0 commit comments

Comments
 (0)