Skip to content

[byol-han] WEEK 15 solutions #1656

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 12, 2025
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
36 changes: 36 additions & 0 deletions binary-tree-level-order-traversal/byol-han.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* https://leetcode.com/problems/binary-tree-level-order-traversal/description/
* 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} root
* @return {number[][]}
*/
var levelOrder = function (root) {
const result = [];
if (!root) return result;

const queue = [root];

while (queue.length > 0) {
const levelSize = queue.length;
const level = [];

for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
level.push(node.val);

if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}

result.push(level);
}

return result;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
* 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 {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function (preorder, inorder) {
// 해시맵을 만들어 중위 순회의 값 -> 인덱스를 빠르게 찾을 수 있도록 함
const inorderMap = new Map();
inorder.forEach((val, idx) => {
inorderMap.set(val, idx);
});

// preorder를 순회할 인덱스
let preorderIndex = 0;

/**
* 재귀 함수: 현재 서브트리의 중위 순회 구간(start ~ end)을 기반으로 트리를 만든다.
*/
function arrayToTree(left, right) {
// 종료 조건: 구간이 잘못되면 노드가 없음
if (left > right) return null;

// preorder에서 현재 루트 값 선택
const rootVal = preorder[preorderIndex];
preorderIndex++; // 다음 호출을 위해 인덱스 증가

// 현재 노드 생성
const root = new TreeNode(rootVal);

// 루트 값의 중위 순회 인덱스 찾기
const index = inorderMap.get(rootVal);

// 왼쪽 서브트리와 오른쪽 서브트리를 재귀적으로 생성
root.left = arrayToTree(left, index - 1);
root.right = arrayToTree(index + 1, right);

return root;
}

// 전체 inorder 범위로 시작
return arrayToTree(0, inorder.length - 1);
};
29 changes: 29 additions & 0 deletions house-robber-ii/byol-han.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* https://leetcode.com/problems/house-robber-ii/submissions/1686583649/
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
if (nums.length === 1) return nums[0];

// Helper to solve the linear house robber problem
function robLinear(houses) {
let prev1 = 0; // dp[i-1]
let prev2 = 0; // dp[i-2]

for (let money of houses) {
let temp = prev1;
prev1 = Math.max(prev1, prev2 + money);
prev2 = temp;
}

return prev1;
}

// Case 1: Exclude last house
let money1 = robLinear(nums.slice(0, nums.length - 1));
// Case 2: Exclude first house
let money2 = robLinear(nums.slice(1));

return Math.max(money1, money2);
};
41 changes: 41 additions & 0 deletions longest-palindromic-substring/byol-han.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* https://leetcode.com/problems/longest-palindromic-substring/submissions/1694755721/
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
// 결과로 반환할 가장 긴 팰린드롬 초기값
let result = '';

// 팰린드롬의 중심에서 양쪽으로 확장하는 함수
function expandAroundCenter(left, right) {
// 왼쪽이 0 이상, 오른쪽이 문자열 길이 이하이며
// 양쪽 문자가 같으면 계속 확장
while (left >= 0 && right < s.length && s[left] === s[right]) {
left--;
right++;
}
// while문을 빠져나오면 팰린드롬이 아님.
// 현재 찾은 팰린드롬 반환
return s.slice(left + 1, right);
}

// 문자열의 각 문자를 중심으로 확장 시도
for (let i = 0; i < s.length; i++) {
// 홀수 길이 팰린드롬 (중심이 한 글자)
const oddPalindrome = expandAroundCenter(i, i);
// 짝수 길이 팰린드롬 (중심이 두 글자)
const evenPalindrome = expandAroundCenter(i, i + 1);

// 더 긴 팰린드롬 선택
if (oddPalindrome.length > result.length) {
result = oddPalindrome;
}
if (evenPalindrome.length > result.length) {
result = evenPalindrome;
}
}

// 결과 반환
return result;
};
40 changes: 40 additions & 0 deletions subtree-of-another-tree/byol-han.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* https://leetcode.com/problems/subtree-of-another-tree/description/
* 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} root
* @param {TreeNode} subRoot
* @return {boolean}
*/
var isSubtree = function (root, subRoot) {
// If the main tree is empty, it can't contain subRoot
if (!root) return false;

// If the trees rooted at current node are the same, return true
if (isSameTree(root, subRoot)) {
return true;
}

// Otherwise, recursively check left and right subtrees
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
};

function isSameTree(s, t) {
// If both nodes are null, trees are identical at this branch
if (!s && !t) return true;

// If only one is null, trees are not identical
if (!s || !t) return false;

// If current node values are different, trees are not identical
if (s.val !== t.val) return false;

// Recursively check left and right children
return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
}