129.Sum Root to Leaf Numbers

Posted smallredness

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了129.Sum Root to Leaf Numbers相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    int sumNumbers(TreeNode* root) {
        return sumNumbersDFS(root, 0);
    }
    int sumNumbersDFS(TreeNode* root, int sum) {
        if (!root) return 0;
        sum = sum * 10 + root->val;
        if (!root->left && !root->right) return sum;
        return sumNumbersDFS(root->left, sum) + sumNumbersDFS(root->right, sum);
    }
};
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        stack<TreeNode*> st{{root}};
        while (!st.empty()) {
            TreeNode *t = st.top(); st.pop();
            if (!t->left && !t->right) {
                res += t->val;
            }
            if (t->right) {
                t->right->val += t->val * 10;
                st.push(t->right);
            }
            if (t->left) {
                t->left->val += t->val * 10;
                st.push(t->left);
            }
        }
        return res;
    }
};

以上是关于129.Sum Root to Leaf Numbers的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode[129]-Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers