Advertisement
yoyo106

Untitled

Apr 17th, 2020
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public int maxLevelSum(TreeNode root) {
  12. if(root == null) return 0;
  13. List<Integer> sums = new ArrayList<>();
  14. Queue<TreeNode> q = new LinkedList<>();
  15. q.offer(root);
  16. while(!q.isEmpty()){
  17. int len = q.size();
  18. int sum = 0;
  19. while(len-->0){
  20. TreeNode cur = q.poll();
  21. sum+=cur.val;
  22. if(cur.left != null)
  23. q.offer(cur.left);
  24. if(cur.right != null)
  25. q.offer(cur.right);
  26. }
  27. sums.add(sum);
  28. }
  29. int ret = 0;
  30. int max = sums.get(0);
  31. for(int i=1;i<sums.size();i++){
  32. if(sums.get(i) > max){
  33. max = sums.get(i);
  34. ret = i+1;
  35. }
  36. }
  37. return ret;
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement