-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindMaxSumInBT.java
More file actions
40 lines (33 loc) · 888 Bytes
/
findMaxSumInBT.java
File metadata and controls
40 lines (33 loc) · 888 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
35
36
37
38
39
40
package Interview;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import Interview.TreeNode;
public class findMaxSumInBT {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
private static int findMaxSum(TreeNode root){
if(root==null){
return 0;
}
int max = 0;
Queue<TreeNode> queue = new LinkedList<>();
HashMap<TreeNode,Integer> sumMap = new HashMap<>();
queue.offer(root);
sumMap.put(root, root.val);
while(!queue.isEmpty()){
TreeNode tmpNode = queue.poll();
max = Math.max(max, sumMap.get(tmpNode));
if(tmpNode.left!=null){
queue.offer(tmpNode.left);
sumMap.put(tmpNode.left,sumMap.get(tmpNode)+tmpNode.left.val);
}
if(tmpNode.right!=null){
queue.offer(tmpNode.right);
sumMap.put(tmpNode.right,sumMap.get(tmpNode)+tmpNode.right.val);
}
}
return max;
}
}