1195. 找出树中每行的最大值
你需要找到在一棵二叉树中,每一行的最大值
样例
样例 1:
输入:
{1,3,2,5,3,#,9}
输出:
[1,3,9]
解释:
1
/ \
3 2
/ \ \
5 3 9
样例 2:
输入:
{1,2,3,4,5,6,#,#,7}
输出:
[1,3,6,7]
解释:
1
/ \
2 3
/ \ /
4 5 6
\
7
输入测试数据 (每行一个参数)如何理解测试数据?
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a root of integer
* @return: return a list of integer
*/
public List<Integer> largestValues(TreeNode root) {
List<Integer> result=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
stack.add(root);
while (true) {
Stack<TreeNode> stack2 = new Stack<>();
int max = 0;
while (!stack.empty()) {
TreeNode treeNode = stack.pop();
if (treeNode==null)continue;
max = Math.max(max, treeNode.val);
stack2.add(treeNode.left);
stack2.add(treeNode.right);
}
if (stack2.empty())break;
result.add(max);
stack=stack2;
}
return result;
}
}