Skip to content

Commit 6cdc0f1

Browse files
committed
Update Solution2.cpp
1 parent 91de513 commit 6cdc0f1

File tree

1 file changed

+32
-24
lines changed

1 file changed

+32
-24
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,35 @@
1-
//Approach 2: Iterative
2-
//Time: O(n)
3-
//Space: O(h)
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
412
class Solution {
5-
public:
6-
int sumOfLeftLeaves(TreeNode* root) {
7-
if (root == nullptr)
8-
return 0;
9-
10-
int ans = 0;
11-
stack<TreeNode*> stack{{root}};
12-
13-
while (!stack.empty()) {
14-
root = stack.top(), stack.pop();
15-
if (root->left) {
16-
if (root->left->left == nullptr && root->left->right == nullptr)
17-
ans += root->left->val;
18-
else
19-
stack.push(root->left);
20-
}
21-
if (root->right)
22-
stack.push(root->right);
13+
public:
14+
int sumOfLeftLeaves(TreeNode* root) {
15+
if (!root) {
16+
return 0;
17+
}
18+
int ans = 0;
19+
stack<TreeNode*> stk{{root}};
20+
while (!stk.empty()) {
21+
root = stk.top(), stk.pop();
22+
if (root->left) {
23+
if (!root->left->left && !root->left->right) {
24+
ans += root->left->val;
25+
} else {
26+
stk.push(root->left);
27+
}
28+
}
29+
if (root->right) {
30+
stk.push(root->right);
31+
}
32+
}
33+
return ans;
2334
}
24-
25-
return ans;
26-
}
2735
};

0 commit comments

Comments
 (0)