-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1302-deepest-leaves-sum.java
More file actions
34 lines (31 loc) · 935 Bytes
/
1302-deepest-leaves-sum.java
File metadata and controls
34 lines (31 loc) · 935 Bytes
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
/**
* 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 maxLevel = depth(root);
return dfs(root, 1, maxLevel);
}
public int depth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(depth(root.left), depth(root.right));
}
public int dfs(TreeNode root, int currLevel, int Level) {
if (root == null) return 0;
if (currLevel == Level) return root.val;
return dfs(root.left, currLevel + 1, Level) +
dfs(root.right, currLevel + 1, Level);
}
}