Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

day22-q2 solution added in python, java #464 #485

Merged
merged 3 commits into from
Jan 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Day-22/q2: Sum of Left Leaves/Tech-neophyte--pj.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
## Python code: Iterative DFS using Stack
```
class Solution(object):
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
stack = [root]
res = 0
while stack:
u = stack.pop()
if u.left:
stack.append(u.left)
if not u.left.left and not u.left.right:
res += u.left.val
if u.right:
stack.append(u.right)
return res
```
## Java code:
```
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}

int sum = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right) + sum;
}
}
```