File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
solution/0500-0599/0515.Find Largest Value in Each Tree Row Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 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+ public class Solution {
11+ // 深度遍历
12+ public List <Integer > largestValues (TreeNode root ) {
13+ List <Integer > list = new ArrayList <>();
14+ dfs (list , root , 0 );
15+ return list ;
16+ }
17+
18+ private void dfs (List <Integer > list , TreeNode root , int level ) {
19+ if (root == null ) {
20+ return ;
21+ }
22+ // 每深入一层,先把那一层的第一个节点加入返回 list中
23+ if (list .size () == level ) {
24+ list .add (root .val );
25+ }
26+ // 此时 size > level ,那么就是开始遍历每一层 的 其他节点(不包括最左边的节点),
27+ // 直接比较list的对应下标(index)的值与当前值就好
28+ else {
29+ list .set (level , Math .max (list .get (level ), root .val ));
30+ }
31+ // 左右子树,深度要+1
32+ dfs (list , root .left , level + 1 );
33+ dfs (list , root .right , level + 1 );
34+ }
35+ }
You can’t perform that action at this time.
0 commit comments