From 4f1140eb39ad67c5d0d6bd3b7dc7a7b0ae48c196 Mon Sep 17 00:00:00 2001 From: Stackingrule <38368554+Stackingrule@users.noreply.github.com> Date: Sat, 2 Jan 2021 19:15:34 +0800 Subject: [PATCH] Add files via upload --- .../Solution.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.cpp diff --git a/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.cpp b/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.cpp new file mode 100644 index 0000000000000..d2a12714894c3 --- /dev/null +++ b/solution/0100-0199/0129.Sum Root to Leaf Numbers/Solution.cpp @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +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; + } + +}; \ No newline at end of file