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

    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]

    经典bfs, 不多说

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<Integer> largestValues(TreeNode root) {
            
            List<Integer> ans = new ArrayList<>();
            if (root == null) return ans;
            Queue<TreeNode> q = new LinkedList<>();
            
            q.offer(root);
            while (!q.isEmpty()) {
                int size = q.size();
                int max = Integer.MIN_VALUE;
                while (size > 0) {
                     TreeNode cur = q.poll();
                     size--;
                     max = Math.max(cur.val, max);
                     if (cur.left != null) {
                        q.offer(cur.left);
                    }
                    if (cur.right != null) {
                        q.offer(cur.right);
                    }
                }
                ans.add(max);
            }
            return ans;
        }
    }
    

      

  • 相关阅读:
    Prime Cryptarithm
    Barn Repair
    Mixing Milk
    June Challenge 2017
    Dual Palindromes
    数学专题
    遗传算法学习
    UVA 11464 暴力+位运算 ***
    233
    hdu 3236 二维背包
  • 原文地址:https://www.cnblogs.com/apanda009/p/7295436.html
Copyright © 2011-2022 走看看