博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
129.Sum Root to Leaf Numbers
阅读量:5232 次
发布时间:2019-06-14

本文共 987 字,大约阅读时间需要 3 分钟。

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
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; }};

转载于:https://www.cnblogs.com/smallredness/p/10677652.html

你可能感兴趣的文章