zoukankan      html  css  js  c++  java
  • leetcode515- Find Largest Value in Each Tree Row- medium

    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]

    算法:

    1.BFS。层级遍历,每层打擂台。

    2.DFS。记录从上到下的深度,每层参数里传下去+1即可。(从下到上的深度是通过回传int返回值来递归实现的)。每次根据当前深度d跟List<Integer>里对应位置的值打擂台。注意List的set用法。list.set(d, Math.max(list.get(d), n.val));

    实现:

    1.BFS

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

    2.DFS

    public class Solution {
        public List<Integer> largestValues(TreeNode root) {
            List<Integer> res = new ArrayList<Integer>();
            helper(root, res, 0);
            return res;
        }
        private void helper(TreeNode root, List<Integer> res, int d){
            if(root == null){
                return;
            }
           //expand list size
            if(d == res.size()){
                res.add(root.val);
            }
            else{
            //or set value
                res.set(d, Math.max(res.get(d), root.val));
            }
            helper(root.left, res, d+1);
            helper(root.right, res, d+1);
        }
    }
  • 相关阅读:
    网站访问量和服务器带宽的选择
    PHP实现四种基本排序算法
    常用的PHP排序算法以及应用场景
    常见的mysql数据库sql语句的编写和运行结果
    MyBatis拦截器:给参数对象属性赋值
    《自律让你自由》摘要
    Java JDK1.5、1.6、1.7新特性整理(转)
    人人都能做产品经理吗?
    Windows下查询进程、端口
    一语收录(2016-09-18)
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7920302.html
Copyright © 2011-2022 走看看