Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions maximum-depth-of-binary-tree/mkwkw.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {

//root가 비어있는 경우
if(root == nullptr)
{
return 0;
}

stack<TreeNode*> nodeStack;
stack<int> depthStack;
int maxDepth = 0;

nodeStack.push(root);
depthStack.push(1);

while(!nodeStack.empty())
{
TreeNode* rootNode = nodeStack.top(); //change root pointer
int rootDepth = depthStack.top();
maxDepth = max(maxDepth, rootDepth);
nodeStack.pop();
depthStack.pop();

//making max depth binary tree
if(rootNode->left != nullptr)
{
nodeStack.push(rootNode->left);
depthStack.push(rootDepth+1);
}

if(rootNode->right != nullptr)
{
nodeStack.push(rootNode->right);
depthStack.push(rootDepth+1);
}

}
return maxDepth;
}
};
39 changes: 39 additions & 0 deletions merge-two-sorted-lists/mkwkw.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
//풀이 참고하였음.
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { //list1, list2 다 포인터
ListNode mergedNode(-1); //mergedNode 객체 선언
ListNode* mergedNodeList = &mergedNode; //node: (merged 객체)의 (주소) (&merged)저장 (객체를 포인터에 넣기)

ListNode* l1 = list1; // 포인터 l1
ListNode* l2 = list2; // 포인터 l2

while (l1 != nullptr && l2 != nullptr) {
//l1, l2 둘 중에 head 값(->val) 값이 작은 것을 node->next에 연결
if (l1->val < l2->val) { // 포인터로 객체의 속성 참조(->)
mergedNodeList->next = l1;
l1 = l1->next;
} else {
mergedNodeList->next = l2;
l2 = l2->next;
}
mergedNodeList = mergedNodeList->next;
}

//남아있는 list를 node->next에 연결
mergedNodeList->next = (l1 != nullptr) ? l1 : l2;
//return the head of the merged linked list (mergeNode -1 다음 것을 가리키는 포인터 next)
return mergedNode.next;

}
};