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
50 changes: 50 additions & 0 deletions Jiho/Day18/Leetcode_100. Same Tree.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// p,q are roots of two binary trees
var isSameTree = function (p, q) {
// 두개다 null인 경우
if (!p && !q) {
return true;
}
// 둘다 null이 아닌 경우
else if (!p !== null && q !== null) {
if (p.val !== q.val) return false;

if (
(p.left !== null && q.left === null) ||
(p.left === null && q.left !== null)
) {
return false;
}
if (
(p.right !== null && q.right === null) ||
(p.right === null && q.right !== null)
) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
// 둘중 하나만 null인 경우
else {
return false;
}
};

// p,q are roots of two binary trees
var isSameTree = function (p, q) {
// #1. p and q are null
if (!p && !q) {
return true;
}
// #2. p and q should not have null + same value
else if (!p || !q || p.val !== q.val) {
return false;
}
// #3. Check left and right validation
else {
// 최적화 방법
if (!isSameTree(p.left, q.left)) {
return false;
}
return isSameTree(p.right, q.right);
// return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
};
32 changes: 32 additions & 0 deletions Jiho/Day18/Leetcode_110. Balanced Binary Tree.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// 왼쪽깊이 구하기 + 오른쪽깊이 구하기

var isBalanced = function (root) {
if (!root) {
return true;
}

// #1. 자신
let l = countNodes(root.left);
let r = countNodes(root.right);

if (Math.abs(l - r) > 1) {
return false;
}
// #2. 왼쪽 오른쪽
return isBalanced(root.left) && isBalanced(root.right);
};

const countNodes = (root, depth = 1) => {
if (!root) {
return 0;
}

if (!root.left && !root.right) {
return depth;
}

return Math.max(
countNodes(root.left, depth + 1),
countNodes(root.right, depth + 1)
);
};