[LeetCode] 1022 - Sum of Root To Leaf Binary Numbers
문제
- 링크: https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/
- 난이도: Easy
- 태그: 트리, 이진트리, 깊이 우선 탐색
- 결과:
Time: 0 ms (100%), Space: 17.1 MB (99.87%)
풀이
class Solution {
public:
int sumRootToLeaf(TreeNode* root) {
return solve(root, 0);
}
int solve(TreeNode* root, int curNum) {
if (root == nullptr)
{
return 0;
}
curNum <<= 1;
curNum |= root->val;
if (root->left == nullptr && root->right == nullptr)
{
return curNum;
}
return solve(root->left, curNum) + solve(root->right, curNum);
}
};
Daily Question이어서 풀었다. 간단한 트리 순회 문제이다. 특별히 주의해야하는 것도 없어서 Easy로 매겨진 것 같은데, 비트 연산이 그렇게 간단하지 않으니(?) Normal로 올리라는 의견도 좀 보였다.
배운 점과 후기
LeetCode 프리미엄을 결제했다. 이제부터 LeetCode 위주로 풀 예정이다.
댓글남기기