Skip to content

Commit c65cfce

Browse files
oris8JooKangsan
authored andcommitted
[oris8] 24.11.26 (#107)
* 102 / Binary Tree Level Order Traversal / Medium / 12m 8s * 572 / Subtree of Another Tree / Easy / 23m 12s * 213 / House Robber II / Medium / 13m 27s * 207 / Course Schedule / Medium / - * 150 / Evaluate Reverse Polish Notation / Medium / 36m 44s
1 parent b5ea5e0 commit c65cfce

10 files changed

+406
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*
9+
* 102 / Binary Tree Level Order Traversal / Medium / 12m 8s
10+
*/
11+
/**
12+
* @param {TreeNode} root
13+
* @return {number[][]}
14+
*/
15+
/**
16+
* Definition for a binary tree node.
17+
* function TreeNode(val, left, right) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.left = (left===undefined ? null : left)
20+
* this.right = (right===undefined ? null : right)
21+
* }
22+
*/
23+
/**
24+
* @param {TreeNode} root
25+
* @return {number[][]}
26+
*/
27+
var levelOrder = function (root) {
28+
if (!root) return [];
29+
30+
const result = [];
31+
const queue = [root];
32+
33+
while (queue.length > 0) {
34+
const levelSize = queue.length;
35+
const currentLevel = [];
36+
37+
for (let i = 0; i < levelSize; i++) {
38+
const node = queue.shift();
39+
currentLevel.push(node.val);
40+
41+
if (node.left) queue.push(node.left);
42+
if (node.right) queue.push(node.right);
43+
}
44+
45+
result.push(currentLevel);
46+
}
47+
48+
return result;
49+
};
50+
51+
// var levelOrder = function(root) {
52+
// const result = [];
53+
54+
// const traverse = (node, level) => {
55+
// if (!node) return;
56+
// if (result.length === level) {
57+
// result.push([]); // 새로운 레벨 생성
58+
// }
59+
// result[level].push(node.val); // 현재 레벨에 값 추가
60+
// traverse(node.left, level + 1); // 왼쪽 자식 탐색
61+
// traverse(node.right, level + 1); // 오른쪽 자식 탐색
62+
// };
63+
64+
// traverse(root, 0);
65+
// return result;
66+
// };
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
*
3+
* 128. Longest Consecutive Sequence
4+
* Medium
5+
* Topics
6+
* Companies
7+
* Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
8+
*
9+
* You must write an algorithm that runs in O(n) time.
10+
* @param {number[]} nums
11+
* @return {number}
12+
*/
13+
var longestConsecutive = function (nums) {
14+
// 중복되는 요소 허용, 빈 배열 허용
15+
if (nums.length === 0) return 0;
16+
17+
const set = new Set(nums);
18+
const sortedSet = Array.from(set).sort((a, b) => a - b);
19+
20+
let maxSequenceLength = 1;
21+
let currentSequence = [sortedSet[0]];
22+
23+
for (let i = 1; i < sortedSet.length; i++) {
24+
const last = currentSequence.pop();
25+
if (last + 1 === sortedSet[i]) {
26+
currentSequence.push(last);
27+
currentSequence.push(sortedSet[i]);
28+
} else {
29+
currentSequence = [sortedSet[i]];
30+
}
31+
maxSequenceLength = Math.max(maxSequenceLength, currentSequence.length);
32+
}
33+
34+
return maxSequenceLength;
35+
};
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
*
3+
* 150 / Evaluate Reverse Polish Notation / Medium / 36m 44s
4+
*
5+
* @param {string[]} tokens
6+
* @return {number}
7+
*/
8+
var evalRPN = function (tokens) {
9+
const operators = {
10+
"+": (a, b) => a + b,
11+
"-": (a, b) => a - b,
12+
"*": (a, b) => a * b,
13+
"/": (a, b) => Math.trunc(a / b),
14+
};
15+
16+
const stack = [];
17+
18+
for (const token of tokens) {
19+
if (operators?.[token]) {
20+
const b = stack.pop();
21+
const a = stack.pop();
22+
stack.push(operators[token](a, b));
23+
} else {
24+
stack.push(+token);
25+
}
26+
}
27+
28+
return stack.pop();
29+
};

oris8/207_course-schedule.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// 207 / Course Schedule / Medium / -
2+
/**
3+
* @param {number} numCourses
4+
* @param {number[][]} prerequisites
5+
* @return {boolean}
6+
*/
7+
8+
/**
9+
* @param {number} numCourses
10+
* @param {number[][]} prerequisites
11+
* @return {boolean}
12+
*/
13+
var canFinish = function (numCourses, prerequisites) {
14+
const graph = new Map();
15+
16+
// 그래프 생성
17+
for (let i = 0; i < numCourses; i++) {
18+
graph.set(i, []);
19+
}
20+
21+
for (const [course, prereq] of prerequisites) {
22+
graph.get(prereq).push(course);
23+
}
24+
25+
// 방문 상태 관리
26+
const visited = new Set(); // 현재 DFS 방문 중인 노드
27+
const completed = new Set(); // 이미 처리 완료된 노드
28+
29+
// 사이클 탐지 함수
30+
const dfs = (course) => {
31+
if (visited.has(course)) return false; // 사이클 발견
32+
if (completed.has(course)) return true; // 이미 확인된 경우
33+
34+
visited.add(course); // 현재 노드 방문 중
35+
for (const nextCourse of graph.get(course)) {
36+
if (!dfs(nextCourse)) return false; // 다음 코스에서 사이클 발견
37+
}
38+
visited.delete(course); // 탐색 완료 후 제거
39+
completed.add(course); // 완료된 노드로 기록
40+
41+
return true;
42+
};
43+
44+
// 각 강좌에 대해 DFS 실행
45+
for (let i = 0; i < numCourses; i++) {
46+
if (!dfs(i)) return false; // 사이클이 존재하면 false 반환
47+
}
48+
49+
return true; // 모든 강좌를 완료할 수 있음
50+
};
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/**
2+
* 208. Implement Trie (Prefix Tree)
3+
Medium
4+
Topics
5+
Companies
6+
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
7+
8+
Implement the Trie class:
9+
10+
Trie() Initializes the trie object.
11+
void insert(String word) Inserts the string word into the trie.
12+
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
13+
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
14+
15+
1 <= word.length, prefix.length <= 2000
16+
word and prefix consist only of lowercase English letters.
17+
At most 3 * 104 calls in total will be made to insert, search, and startsWith.
18+
*/
19+
20+
// var Trie = function() {
21+
// node
22+
// };
23+
24+
class TrieNode {
25+
constructor() {
26+
this.children = {};
27+
this.words = new Set();
28+
}
29+
}
30+
31+
class Trie {
32+
constructor() {
33+
this.root = new TrieNode();
34+
}
35+
36+
traverse(word) {
37+
let node = this.root;
38+
for (let char of word) {
39+
node = node.children[char];
40+
if (!node) return null;
41+
}
42+
return node;
43+
}
44+
}
45+
46+
/**
47+
* @param {string} word
48+
* @return {void}
49+
*/
50+
Trie.prototype.insert = function (word) {
51+
let node = this.root;
52+
for (const char of word) {
53+
if (!node.children[char]) {
54+
node.children[char] = new TrieNode();
55+
}
56+
node = node.children[char];
57+
}
58+
node.words.add(word);
59+
};
60+
61+
/**
62+
* @param {string} word
63+
* @return {boolean}
64+
*/
65+
Trie.prototype.search = function (word) {
66+
let node = this.traverse(word);
67+
return !!node && node.words.has(word);
68+
};
69+
70+
/**
71+
* @param {string} prefix
72+
* @return {boolean}
73+
*/
74+
Trie.prototype.startsWith = function (prefix) {
75+
let node = this.traverse(prefix);
76+
return !!node;
77+
};
78+
79+
/**
80+
* Your Trie object will be instantiated and called as such:
81+
* var obj = new Trie()
82+
* obj.insert(word)
83+
* var param_2 = obj.search(word)
84+
* var param_3 = obj.startsWith(prefix)
85+
*/

oris8/213_house-robber-ii.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* 213 / House Robber II / Medium / 13m 27s
3+
/**
4+
* @param {number[]} nums
5+
* @return {number}
6+
*/
7+
var rob = function (nums) {
8+
// T(n) = Math.max(T(n-1), T(n-2) + n)
9+
if (nums.length <= 2) return Math.max(nums[0], nums?.[1] || 0);
10+
11+
const results = [nums[0], Math.max(nums[0], nums[1])];
12+
const not1results = [0, nums[1]];
13+
for (let i = 2; i < nums.length; i++) {
14+
results[i] = Math.max(results[i - 1], results[i - 2] + nums[i]);
15+
not1results[i] = Math.max(not1results[i - 1], not1results[i - 2] + nums[i]);
16+
}
17+
18+
return Math.max(results[nums.length - 2], not1results[nums.length - 1]);
19+
};

oris8/226_invert-binary-tree.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {TreeNode}
12+
*/
13+
var invertTree = function (root) {
14+
if (root) {
15+
[root.right, root.left] = [invertTree(root.left), invertTree(root.right)];
16+
}
17+
// if (!root) return null;
18+
// [root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
19+
20+
return root;
21+
};

oris8/371_sum-of-two-integers.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* 371. Sum of Two Integers
3+
* Medium
4+
*
5+
* Given two integers a and b, return the sum of the two integers without using the operators + and -.
6+
*
7+
* -1000 <= a, b <= 1000
8+
*
9+
* @param {number} a
10+
* @param {number} b
11+
* @return {number}
12+
*/
13+
var getSum = function (a, b) {
14+
// 비트 연산 사용
15+
/**
16+
*
17+
* XOR :각 비트를 비교하여, 두 비트가 서로 다르면 1을 반환하고, 같으면 0을 반환
18+
* === carry(올림)를 무시한 덧셈과 동일한 결과
19+
*
20+
* AND :두 비트가 모두 1인 경우
21+
*
22+
* 자리올림은 두 비트가 모두 1일때 발생하므로 AND 연산을 통해서 이를 확인하고, 두 비트가 모두 1일 경우 자리올림 수행 (<<)
23+
*
24+
*/
25+
26+
return b === 0 ? a : getSum(a ^ b, (a & b) << 1);
27+
};
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
*
3+
* 543. Diameter of Binary Tree
4+
Easy
5+
Topics
6+
Companies
7+
Given the root of a binary tree, return the length of the diameter of the tree.
8+
9+
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
10+
11+
The length of a path between two nodes is represented by the number of edges between them.
12+
13+
The number of nodes in the tree is in the range [1, 104].
14+
-100 <= Node.val <= 100
15+
16+
* Definition for a binary tree node.
17+
* function TreeNode(val, left, right) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.left = (left===undefined ? null : left)
20+
* this.right = (right===undefined ? null : right)
21+
* }
22+
*/
23+
/**
24+
* @param {TreeNode} root
25+
* @return {number}
26+
*/
27+
var diameterOfBinaryTree = function (root) {
28+
let maxDiameter = 0;
29+
const getBinaryTreeHeight = (node) => {
30+
if (!node) return 0;
31+
32+
// 현재 노드부터 높이를 재귀적으로 계산
33+
const right = getBinaryTreeHeight(node.right);
34+
const left = getBinaryTreeHeight(node.left);
35+
36+
maxDiameter = Math.max(maxDiameter, right + left);
37+
38+
// 현재 노드를 포함하기 위해 + 1
39+
return Math.max(right, left) + 1;
40+
};
41+
42+
getBinaryTreeHeight(root);
43+
return maxDiameter;
44+
};

0 commit comments

Comments
 (0)