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]
    题目含义:从上到下找到每行的最大值
    方法一:DFS
    参数d表示层数的索引,第一行对应的d为0
     1     private void largestValue(TreeNode root, List<Integer> res, int d){
     2         if(root == null){
     3             return;
     4         }
     5         //expand list size
     6         if(d == res.size()){
     7             res.add(root.val); //在最下面添加新的行
     8         }
     9         else{
    10             //or set value
    11             res.set(d, Math.max(res.get(d), root.val)); //当前节点值处于第(d+1)层,如果当前值大于res中保存的值,则替换成最大值
    12         }
    13         largestValue(root.left, res, d+1);
    14         largestValue(root.right, res, d+1);
    15     }
    16     
    17     
    18     public List<Integer> largestValues(TreeNode root) {
    19         List<Integer> res = new ArrayList<Integer>();
    20         largestValue(root, res, 0);
    21         return res;     
    22     }

    方法二:

     1     public List<Integer> largestValues(TreeNode root) {
     2         Queue<TreeNode> queue = new LinkedList<TreeNode>();
     3         List<Integer> res = new ArrayList<Integer>();
     4         if (root == null) return res;
     5         queue.add(root);
     6         while (!queue.isEmpty()) {
     7             int largestElement = Integer.MIN_VALUE;
     8             int queueSize = queue.size();
     9             for (int i=0;i<queueSize;i++) {
    10                 TreeNode cur = queue.poll();
    11                 largestElement = Math.max(cur.val, largestElement);
    12                 if (cur.left != null) queue.add(cur.left);
    13                 if (cur.right != null) queue.add(cur.right);
    14             }
    15             res.add(largestElement);
    16         }
    17         return res;
    18     }
    
    
  • 相关阅读:
    MySQL详细安装(windows)
    深入理解java虚拟机
    java语言实现机制
    java基本类型的长度
    关于SQLite数据库 字段 DateTime 类型
    "初识".Net Winfom
    Linux Shell脚本编程while语句
    mysql主从搭建
    oracle dg状态检查及相关命令
    Oracle 11.2.0.4单实例打补丁
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7714343.html
Copyright © 2011-2022 走看看