-
Notifications
You must be signed in to change notification settings - Fork 823
/
Copy pathSumofLeftLeaves.java
48 lines (42 loc) · 966 Bytes
/
SumofLeftLeaves.java
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
package tree;
/**
* Created by gouthamvidyapradhan on 13/12/2017. Find the sum of all left leaves in a given binary
* tree.
*
* <p>Example:
*
* <p>3 / \ 9 20 / \ 15 7
*
* <p>There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
*/
public class SumofLeftLeaves {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {}
public int sumOfLeftLeaves(TreeNode root) {
return inorder(root, false);
}
private int inorder(TreeNode node, boolean isLeft) {
if (node != null) {
if (node.left == null && node.right == null) {
if (isLeft) {
return node.val;
} else return 0;
}
return inorder(node.left, true) + inorder(node.right, false);
}
return 0;
}
}