-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
36 lines (31 loc) · 1.08 KB
/
Solution.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
/**
* 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> res = new ArrayList<Integer>();
LinkedList<TreeNode> stack = new LinkedList<TreeNode>(),
nextStack = new LinkedList<TreeNode>();
Integer maxValue = null;
if (root != null) stack.addLast(root);
while (stack.size() > 0) {
TreeNode node = stack.pop();
maxValue = maxValue == null ? node.val : Math.max(maxValue, node.val);
if (node.left != null) nextStack.addLast(node.left);
if (node.right != null) nextStack.addLast(node.right);
if (stack.size() == 0) {
res.add(maxValue);
stack = nextStack;
nextStack = new LinkedList<TreeNode>();
maxValue = null;
}
}
return res;
}
}