zoukankan      html  css  js  c++  java
  • LeetCode赛题515----Find Largest Element in Each Row

    问题描述

    You need to find the largest element in each row of a Binary Tree.

    Example:
    Input: 
    
          1
         / 
        2   3
       /      
      5   3   9 
    
    Output: [1, 3, 9]
    

    算法分析

    使用两个队列,逐层遍历二叉树的各个节点,每个队列中的节点都是同一层的节点,在遍历一层时,找出该层最大的节点值加入ArrayList中。

    Java算法实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int[] findValueMostElement(TreeNode root) {
            if(root==null){
        		int[] tmp=new int[0];
        		return tmp;
        	}
            ArrayList<Integer>arr=new ArrayList<>();
            Queue<TreeNode>que1=new LinkedList<>();
            Queue<TreeNode>que2=new LinkedList<>();
            que1.add(root);
            int max;
            while(!que1.isEmpty()||!que2.isEmpty()){
            	max=Integer.MIN_VALUE;
            	if(!que1.isEmpty()){
            		while(!que1.isEmpty()){
            			TreeNode node=que1.poll();
            			if(node.val>max){	//找到该层的最大值
            				max=node.val;
            			}
            			if(node.left!=null){
            				que2.add(node.left);
            			}
            			if(node.right!=null){
            				que2.add(node.right);
            			}
            		}
            		arr.add(max);
            	}
            	else if(!que2.isEmpty()){
            		while(!que2.isEmpty()){
            			TreeNode node=que2.poll();
            			if(node.val>max){
            				max=node.val;
            			}
            			if(node.left!=null){
            				que1.add(node.left);
            			}
            			if(node.right!=null){
            				que1.add(node.right);
            			}
            		}
            		arr.add(max);
            	}
            }
            int [] ans=new int[arr.size()];
            for(int i=0;i<ans.length;i++){
            	ans[i]=arr.get(i);
            }
            return ans;
        }
    }
  • 相关阅读:
    BZOJ 4032: [HEOI2015]最短不公共子串 (dp*3 + SAM)
    后缀自动机详解!
    BZOJ 3926: [Zjoi2015]诸神眷顾的幻想乡(广义后缀自动机 多串)
    BZOJ 3938 Robot
    [JSOI2008]Blue Mary开公司
    [ZJOI2017]树状数组
    [JSOI2015]非诚勿扰
    [HNOI2011]任务调度
    BZOJ 3680 吊打XXX
    POJ 3318 Matrix Multiplication
  • 原文地址:https://www.cnblogs.com/dongling/p/6391145.html
Copyright © 2011-2022 走看看