Skip to content

Commit 91de513

Browse files
AlleyNawazyanglbme
authored andcommitted
Create Solution2.cpp
1 parent 90fb109 commit 91de513

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//Approach 2: Iterative
2+
//Time: O(n)
3+
//Space: O(h)
4+
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);
23+
}
24+
25+
return ans;
26+
}
27+
};

0 commit comments

Comments
 (0)