-
Notifications
You must be signed in to change notification settings - Fork 5
/
1302. Deepest Leaves Sum.java
46 lines (46 loc) · 1.33 KB
/
1302. Deepest Leaves Sum.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
/**
* 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 deepestLeavesSum(TreeNode root) {
int height = getHeight(root);
int a = _deepestLeavesSum(root, height, 0);
return a;
}
private int getHeight(TreeNode root) {
if (root == null) return -1;
// faith
int lh = getHeight(root.left);
int rh = getHeight(root.right);
return Math.max(lh, rh) + 1;
}
private int _deepestLeavesSum(TreeNode root, int height, int curlevel) {
if (root == null) return 0;
if (curlevel == height && root.left == null && root.right == null) {
return root.val;
}
// faith
int leftLeaveSum = _deepestLeavesSum(root.left, height, curlevel + 1);
int rightLeaveSum = _deepestLeavesSum(root.right, height, curlevel + 1);
int myres = leftLeaveSum + rightLeaveSum;
return myres;
}
}