https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/description/
/**
* 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> ans=new ArrayList<Integer>();
if(root==null)
{
return ans;
}
Queue<TreeNode> queue=new ArrayDeque<TreeNode>();
queue.offer(root);
while(queue.size()!=0)
{
int length=queue.size();
int res=-2147483648;
while(length>0)
{
TreeNode t=queue.poll();
int now=t.val;
if(now>res)
{
res=now;
}
if(t.left!=null)
{
queue.offer(t.left);
}
if(t.right!=null)
{
queue.offer(t.right);
}
length--;
}
ans.add(res);
}
return ans;
}
}
思路:
1.使用隊列實現對二叉樹的層序遍歷
2.對於每一層來說選擇一個最大值 所以需要分隔開每一層 使用的辦法是記錄每一層的元素數 然後在這n個數中找最大值
方法很多 也可以在List中加入分隔符來區分層 或是建立數組來與List中的元素一一對應地記錄層數之後再處理等等
3.題目給出的測試用例中有負數 所以對比時初始值設爲了int最小值