赞
踩
/** * 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 maxLevelSum(TreeNode root) { int res = 0; int maxVal = Integer.MIN_VALUE; int depth = 0; Deque<TreeNode> deque = new ArrayDeque<>(); deque.offerLast(root); while (!deque.isEmpty()) { depth++; int size = deque.size(); int sum = 0; for (int i = 0; i < size; i++) { TreeNode node = deque.pollFirst(); sum += node.val; if (node.left != null) { deque.offerLast(node.left); } if (node.right != null) { deque.offerLast(node.right); } } if (sum > maxVal) { res = depth; maxVal = sum; } } return res; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。