๐ณ ์ด๋ณด์์ฉ ๊ฐ์ด๋ 'Root To Leaf Binary Numbers์ ํฉ' - Problem 1022 (C++, Python, JavaScript)
Source: Dev.to
๋ฌธ์ ๊ฐ์
์ด์ง ํธ๋ฆฌ๋ ๊ณ์ธตํ ๋ฐ์ดํฐ ๊ตฌ์กฐ์ ํต์ฌ์ด๋ฉฐ, ํธ๋ฆฌ๋ฅผ ์ํํ๋ ๋ฐฉ๋ฒ์ ์ดํดํ๋ ๊ฒ์ ๋ชจ๋ ๊ฐ๋ฐ์์๊ฒ ๊ธฐ๋ณธ์ ์ธ ๊ธฐ์ ์
๋๋ค.
์ด ๋ฌธ์ ์์๋ ๋ฃจํธ์์ ๋ฆฌํ๊น์ง์ ๊ฐ ๊ฒฝ๋ก๊ฐ ํ๋์ ์ด์ง์๋ฅผ ๋ํ๋
๋๋ค. ๋ชจ๋ ์ด๋ฌํ ์ด์ง์์ ํฉ์ ๊ตฌํ๋ ๊ฒ์ด ๋ชฉํ์
๋๋ค.
์ ๊ทผ ๋ฐฉ๋ฒ
ํธ๋ฆฌ๋ฅผ ์ํํ๋ฉด์ ์ด์ง์๋ฅผ ๋ง๋ค์ด ๋๊ฐ๋ ๊ฒ์ด ํต์ฌ ์์ด๋์ด์ ๋๋ค:
- ํ ๋ ๋ฒจ ์๋๋ก ๋ด๋ ค๊ฐ ๋ ํ์ฌ ๊ฐ์ ์ผ์ชฝ์ผ๋ก ํ ๋นํธ ์ด๋(โฏ*2โฏ)ํ๊ณ ๋ ธ๋์ ๋นํธ๋ฅผ ๋ํฉ๋๋ค.
- ๊น์ด ์ฐ์ ํ์(DFS)์ ์ฌ์ฉํด ๊ฐ ๊ฐ์ง๋ฅผ ํ์ํฉ๋๋ค.
- โํ์ฌ ๊ฐโ์ ์ฌ๊ท ํธ์ถ์ ์ธ์๋ก ์ ๋ฌํฉ๋๋ค.
- ๋ฆฌํ ๋ ธ๋์ ๋๋ฌํ๋ฉด ๋์ ๋ ๊ฐ์ ์ ์ฒด ํฉ์ ๋ํฉ๋๋ค.
ํต์ฌ ๊ฐ๋
- ์ ์ ์ํ(Preโorder Traversal) โ ํ์ฌ ๋ ธ๋๋ฅผ ์์๋ณด๋ค ๋จผ์ ์ฒ๋ฆฌํฉ๋๋ค.
- ๋์ฐ๊ธฐ ํจํด(Accumulator Pattern) โ ํ์ฌ ๊ฒฝ๋ก ๊ฐ์ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌํด ์ ์ญ ์ํ๋ฅผ ์ฌ์ฉํ์ง ์์ต๋๋ค.
- ๋นํธ ์ฐ์ฐ(Bit Manipulation) โ
val = (val * 2) + bit์ ๋นํธ ์ํ์ค๋ฅผ 10์ง์๋ก ๋ณํํฉ๋๋ค.
์์
๋ฃจํธ๊ฐ 1์ด๊ณ ๋ฆฌํ๊ฐ ๋ง๋๋ ๊ฒฝ๋ก๊ฐ (1,0,0), (1,0,1), (1,1,0), (1,1,1) ์ธ ํธ๋ฆฌ๋ฅผ ์๊ฐํด ๋ด
์๋ค.
- ๋ฃจํธ(
1)์์ ์์: ํ์ฌ ๊ฐ =โฏ1. - ์ผ์ชฝ ์์(
0)์ผ๋ก ์ด๋:1โฏรโฏ2โฏ+โฏ0 = 2. - ์ผ์ชฝ ๋ฆฌํ(
0):2โฏรโฏ2โฏ+โฏ0 = 4โ 4๋ฅผ ๋ํจ. - ์ค๋ฅธ์ชฝ ๋ฆฌํ(
1):2โฏรโฏ2โฏ+โฏ1 = 5โ 5๋ฅผ ๋ํจ. - ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ์์๋ ๋์ผํ๊ฒ ์งํ โ ๊ฐ์โฏ6๊ณผโฏ7.
์ ์ฒด ํฉ =โฏ4โฏ+โฏ5โฏ+โฏ6โฏ+โฏ7 = 22.
C++ ํ์ด
class Solution {
public:
int sumRootToLeaf(TreeNode* root) {
int totalSum = 0;
dfs(root, 0, totalSum);
return totalSum;
}
private:
void dfs(TreeNode* node, int currentVal, int& totalSum) {
if (node == nullptr) return;
// Shift left (multiply by 2) and add the current node's bit
currentVal = currentVal * 2 + node->val;
// If it's a leaf node, add the accumulated value to the total
if (node->left == nullptr && node->right == nullptr) {
totalSum += currentVal;
return;
}
dfs(node->left, currentVal, totalSum);
dfs(node->right, currentVal, totalSum);
}
};
Python ํ์ด
class Solution:
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
self.total_sum = 0
def dfs(node, current_val):
if not node:
return
# Binary shift logic: current_val * 2 is equivalent to current_val {
if (!node) return;
// Build the number as we descend
currentVal = (currentVal * 2) + node.val;
// If both children are null, we are at a leaf
if (!node.left && !node.right) {
totalSum += currentVal;
return;
}
dfs(node.left, currentVal);
dfs(node.right, currentVal);
};
dfs(root, 0);
return totalSum;
};
์ ์ด ๋ฌธ์ ๊ฐ ์ค์ํ๊ฐ
์ด โEasyโ ๋ฑ๊ธ ๋ฌธ์ ๋ ๊ธฐ์ ๋ฉด์ ์์ ์ธ๊ธฐ๊ฐ ๋์๋ฐ, ๊ทธ ์ด์ ๋ ๋ค์ ๋ ๊ฐ์ง๋ฅผ ๋์์ ํ๊ฐํ๊ธฐ ๋๋ฌธ์ ๋๋ค:
- ํธ๋ฆฌ ์ฌ๊ท(DFS) ๊ตฌํ ๋ฅ๋ ฅ.
- ์ด์ง์ ๊ตฌ์ฑ ๋ฐ ๋นํธ ์ฐ์ฐ์ ๋ํ ์ดํด.
์ ์ฌํ ๋ก์ง์ ๋ฐ์ดํฐ ์์ถ์ ์ํ ํํ๋ง ์ฝ๋ฉ์ด๋ IP ๋ผ์ฐํ ํ ์ด๋ธ(ํธ๋ผ์ด)๊ณผ ๊ฐ์ด ์ด์ง ํ๋ฆฌํฝ์ค๋ฅผ ํธ๋ฆฌ ํํ๋ก ์ ์ฅํด ๋น ๋ฅด๊ฒ ์กฐํํ๋ ์ค์ ์์คํ ์์๋ ๋ํ๋ฉ๋๋ค. ์ด ํจํด์ ๋ง์คํฐํ๋ฉด ๋ณด๋ค ๋ณต์กํ ์์คํ ์ค๊ณ ๊ณผ์ ์ ๋ํ ํํํ ๊ธฐ๋ฐ์ ๋ค์ง ์ ์์ต๋๋ค.