-
[LeetCode] 129. Sum Root to Leaf NumbersLeetCode 2021. 11. 3. 11:22728x90
https://leetcode.com/problems/sum-root-to-leaf-numbers/
Sum Root to Leaf Numbers - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Sum Root to Leaf Numbers - Medium


root-leaf 노드부터 방문한 노드들을 쭉 나열한 값을 모두 더하는 문제다.
아주아주 간단하다. root부터 왼쪽, 오른쪽 자식을 체크해 있다면 그 자식들의 값을 자신의값*10 만큼 더해주고,
왼쪽,오른쪽 자식이 없다면 leaf로 판단하여 return값에 더해주자.
class Solution { public: long ret = 0; int sumNumbers(TreeNode* root) { run(root); return this->ret; } void run(TreeNode* node) { if (node->left) node->left->val += node->val*10, run(node->left); if (node->right) node->right->val += node->val*10, run(node->right); if (!node->left && !node->right) this->ret+=node->val; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 1346. Check If N and Its Double Exist (0) 2021.11.04 [LeetCode] 404. Sum of Left Leaves (0) 2021.11.04 [LeetCode] 1481. Least Number of Unique Integers after K Removals (0) 2021.11.01 [LeetCode] 1047. Remove All Adjacent Duplicates In String (0) 2021.11.01 [LeetCode] 130. Surrounded Regions (0) 2021.11.01