Leetcode-515. Find Largest Element in Each Row

来源:互联网 发布:设置数据有效性 编辑:程序博客网 时间:2024/05/17 04:52

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

You need to find the largest value in each row of a binary tree.

Example:

Input:           1         / \        3   2       / \   \        5   3   9 Output: [1, 3, 9]
这个题目和刚刚那个题目一样,用一个队列保存子节点,采用广度优先的方式遍历。每一层遍历的时候同时考虑每层的最大值。

public class Solution {    public int[] findValueMostElement(TreeNode root) {        Queue<TreeNode> queue = new LinkedList<TreeNode>();        if(root != null)            queue.add(root);        List<Integer> results = new ArrayList<Integer>();        while(queue.size() != 0){            int size = queue.size();            int maxNum = Integer.MIN_VALUE;            for(int i = 0; i < size; i++){                TreeNode node = queue.poll();                if(node.val >= maxNum) maxNum = node.val;                if(node.left!= null)queue.add(node.left);                if(node.right!=null)queue.add(node.right);            }            results.add(maxNum);        }        int[] temps = new int[results.size()];        for(int i = 0; i < temps.length; i ++)            temps[i] = results.get(i);                    return temps;    }}




0 0
原创粉丝点击