코딩테스트 준비/leetcode

129. Sum Root to Leaf Numbers

MAKGA 2021. 8. 2. 19:35
320x100

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

 

이진트리의 root가 주어졌을 때, root부터 leaf까지 발생하는 unique한 path들의 val을 각 자리수로 대입해 한 정수로 만들고, 모든 정수의 합을 반환하는 문제다.

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void solve(TreeNode* node, int num) {
        if (!node) {
            return;
        }
        
        num = num * 10 + node->val;
        
        if (!node->left && !node->right)
        {
            sum_ += num;
            return;
        }
        
        solve(node->left, num);
        solve(node->right, num);
    }
    
    int sumNumbers(TreeNode* root) {
        sum_ = 0;
        solve(root, 0);
        return sum_;
    }

private:
    int sum_;
};

 

320x100

'코딩테스트 준비 > leetcode' 카테고리의 다른 글

15. 3Sum  (0) 2021.08.04
70. Climbing Stairs  (0) 2021.08.03
230. Kth Smallest Element in a BST  (0) 2021.08.01
107. Binary Tree Level Order Traversal II  (0) 2021.07.31
199. Binary Tree Right Side View  (0) 2021.07.30