zoukankan      html  css  js  c++  java
  • LeetCode 515. Find Largest Value in Each Tree Row

    515. Find Largest Value in Each Tree Row

    Description Submission Solutions

    • Total Accepted: 3804
    • Total Submissions: 7252
    • Difficulty: Medium
    • Contributors: love_FDU_llp

    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] 

    Subscribe to see which companies asked this question.

    【题目分析】
    给定一颗二叉树,返回二叉树中每一层的最大值。
    【思路】
    这是一个典型的二叉树层序遍历的问题,需要使用队列来解决。关于java队列的使用,计划详细了解一下。
    【java代码】
     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<Integer> largestValues(TreeNode root) {
    12         List<Integer> res = new ArrayList<>();
    13         Queue<TreeNode> queue = new LinkedList<>();
    14         
    15         if(root != null) queue.offer(root);
    16         
    17         while(!queue.isEmpty()) {
    18             int max = Integer.MIN_VALUE;
    19             int size = queue.size();
    20             for(int i = 0; i < size; i++) {
    21                 TreeNode node = queue.poll();
    22                 max = Math.max(max, node.val);
    23                 if(node.right != null) queue.offer(node.right);
    24                 if(node.left != null) queue.offer(node.left);
    25             }
    26             res.add(max);
    27         }
    28         
    29         return res;
    30     }
    31 }
     
  • 相关阅读:
    Python-Image 基本的图像处理操作
    剪枝
    poj1182(食物链)续
    HLG2035广搜
    HLG2040二叉树遍历已知前中,求后
    先序,中序,后序,已知两者求第三者
    C++中new的解说
    僵尸进程
    HLG2062(make,heap问题)
    make_head,,,pop_head,,,push_head,,,sort_head..
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6418921.html
Copyright © 2011-2022 走看看