-
Notifications
You must be signed in to change notification settings - Fork 0
/
515.在每个树行中找最大值.java
61 lines (53 loc) · 1.4 KB
/
515.在每个树行中找最大值.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import javax.swing.tree.TreeNode;
import apple.laf.JRSUIUtils.Tree;
/*
* @lc app=leetcode.cn id=515 lang=java
*
* [515] 在每个树行中找最大值
*/
// @lc code=start
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root == null){
return result;
}
Queue<TreeNode> list = new LinkedList<>();
list.offer(root);
TreeNode temp = null;
int max = list.peek().val;
List<TreeNode> tempList = new ArrayList<>();
while(!list.isEmpty()){
temp = list.poll();
max = Math.max(max, temp.val);
if(temp.left!=null){
tempList.add(temp.left);
}
if(temp.right!= null){
tempList.add(temp.right);
}
if(list.isEmpty()){
list.addAll(tempList);
tempList = new ArrayList<>();
result.add(max);
max = list.isEmpty() ? 0 : list.peek().val;
}
}
return result;
}
}
// @lc code=end