Leetcode/Top Interview 150

[Binary Tree General][Medium] 129. Sum Root to Leaf Numbers

자전거통학 2024. 6. 11. 04:36

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.