https://leetcode.com/problems/sum-root-to-leaf-numbers/description
여러 방법이 있을 수 있지만, 직관적인 방법으로 풀어본다.
Codes
더보기
void dfs(TreeNode* node, vector<int>& vBuff, long& sum)
{
if(node == nullptr)
return;
vBuff.push_back(node->val);
if(node->left==nullptr && node->right==nullptr)
{
long val = 0;
long digit = 1;
for(int q = vBuff.size()-1; q >= 0; --q)
{
val += vBuff[q]*digit;
digit *= 10;
}
sum += val;
}
else
{
if(node->left != nullptr) dfs(node->left, vBuff, sum);
if(node->right != nullptr) dfs(node->right, vBuff, sum);
}
vBuff.pop_back();
}
int sumNumbers(TreeNode* root) {
vector<int> vBuff;
long sum = 0;
dfs(root, vBuff, sum);
return sum;
}
Result.
'Leetcode > Top Interview 150' 카테고리의 다른 글
[Binary Tree BFS][Easy] 637. Average of Levels in Binary Tree (0) | 2024.06.14 |
---|---|
[Binary Tree General][Medium] 173. Binary Search Tree Iterator (1) | 2024.06.13 |
[Binary Tree General][Easy] 112. Path Sum (1) | 2024.06.02 |
[Binary Tree General][Medium] 117. Populating Next Right Pointers in Each Node II (0) | 2024.06.01 |
[Binary Tree General][Easy] 226. Invert Binary Tree (0) | 2024.05.29 |