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
81 changes: 81 additions & 0 deletions reorder-list/smosco.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/

/**
* 방법 1: 반으로 나누기 + 뒤집기 + 합치기
* 시간 복잡도: O(n)
* 공간 복잡도: O(1)
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderList = function (head) {
if (!head || !head.next) return;

// 1. 중간 지점 찾기 (slow-fast pointer)
let slow = head,
fast = head;
while (fast.next && fast.next.next) {
slow = slow.next;
fast = fast.next.next;
}

// 2. 뒷부분 리스트 분리 및 뒤집기
let second = slow.next;
slow.next = null;

let prev = null;
while (second) {
let temp = second.next;
second.next = prev;
prev = second;
second = temp;
}

// 3. 두 리스트 합치기
let first = head;
second = prev;
while (second) {
let temp1 = first.next;
let temp2 = second.next;
first.next = second;
second.next = temp1;
first = temp1;
second = temp2;
}
};

/**
* 방법 2: Stack 사용
* 시간 복잡도: O(n)
* 공간 복잡도: O(n)
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderListStack = function (head) {
if (!head || !head.next) return;

// 모든 노드를 스택에 저장
let stack = [];
let curr = head;
while (curr) {
stack.push(curr);
curr = curr.next;
}

// 앞에서부터, 뒤에서부터 번갈아 연결
let len = stack.length;
curr = head;
for (let i = 0; i < Math.floor(len / 2); i++) {
let last = stack.pop();
let temp = curr.next;
curr.next = last;
last.next = temp;
curr = temp;
}
curr.next = null; // 마지막 노드 처리
};
32 changes: 32 additions & 0 deletions same-tree/smosco.js
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저와 정확히 같은 방식을 사용하셔서 동질감이 들었습니다ㅋㅋ

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
// 두 노드가 모두 null이면 같은 트리
if (p === null && q === null) {
return true;
}

// 하나만 null이면 다른 트리
if (p === null || q === null) {
return false;
}

// 값이 다르면 다른 트리
if (p.val !== q.val) {
return false;
}

// 왼쪽과 오른쪽 서브트리를 재귀적으로 비교
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};