@@ -246,4 +246,48 @@ int sumOfLeftLeaves(struct TreeNode* root) {
246
246
247
247
<!-- tabs:end -->
248
248
249
+ ### Solution 2
250
+
251
+ <!-- tabs:start -->
252
+
253
+ ```cpp
254
+ /**
255
+ * Definition for a binary tree node.
256
+ * struct TreeNode {
257
+ * int val;
258
+ * TreeNode *left;
259
+ * TreeNode *right;
260
+ * TreeNode() : val(0), left(nullptr), right(nullptr) {}
261
+ * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
262
+ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
263
+ * };
264
+ */
265
+ class Solution {
266
+ public:
267
+ int sumOfLeftLeaves(TreeNode* root) {
268
+ if (!root) {
269
+ return 0;
270
+ }
271
+ int ans = 0;
272
+ stack<TreeNode*> stk{{root}};
273
+ while (!stk.empty()) {
274
+ root = stk.top(), stk.pop();
275
+ if (root->left) {
276
+ if (!root->left->left && !root->left->right) {
277
+ ans += root->left->val;
278
+ } else {
279
+ stk.push(root->left);
280
+ }
281
+ }
282
+ if (root->right) {
283
+ stk.push(root->right);
284
+ }
285
+ }
286
+ return ans;
287
+ }
288
+ };
289
+ ```
290
+
291
+ <!-- tabs:end -->
292
+
249
293
<!-- end -->
0 commit comments