-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay-24 Sum of Left Leaves
51 lines (43 loc) · 1.27 KB
/
Day-24 Sum of Left Leaves
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root==null) return 0;
if(root.left!=null && root.left.left==null && root.left.right==null)
return root.left.val+sumOfLeftLeaves(root.right);
return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
}
}
class Solution {
private boolean isLeaf(TreeNode node) {
return node != null && node.left == null && node.right == null;
}
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int total = 0;
Deque<TreeNode> queue = new ArrayDeque<>();
queue.push(root);
while (!queue.isEmpty()) {
TreeNode subRoot = queue.pop();
if (isLeaf(subRoot.left)) {
total += subRoot.left.val;
}
if (subRoot.right != null) queue.push(subRoot.right);
if (subRoot.left != null) queue.push(subRoot.left);
}
return total;
}
}