题解 | #重量级的一层#
重量级的一层
https://www.nowcoder.com/practice/193372871b09426ab9ea805f0fd44d5c
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ public int maxLevelSum (TreeNode root) { // write code here List<Long> list = new ArrayList<>(); levelOrder(root, 0, list); int size = list.size(), ans = size; long max = list.get(size - 1); for (int i = size - 2; i >= 0; i--) { long x = list.get(i); if (x > max) { max = x; ans = i + 1; } } return ans; } private void levelOrder(TreeNode root, int level, List<Long> list) { if (root == null) return; if (level == list.size()) list.add(0L); list.set(level, list.get(level) + root.val); levelOrder(root.left, level + 1, list); levelOrder(root.right, level + 1, list); } }
- 利用二叉树的层序遍历,计算二叉树每一层节点数值的累加和,将每一层的累加和存储到一个List集合中
- 逆序遍历List集合,确定最大值以及所在层
线性表基础 文章被收录于专栏
链表、递归、栈