• 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);
        }
    }
  • 相关阅读:
    js 数组相减
    js 对象数组去重
    vue 首次不触发watch的解决方法
    "神药"推荐--紫花地丁
    openstack 平台添加 nvidia vGPU
    string易错点整理总结
    CentOS安装图形界面
    CentOs安装ssh和scp
    数组把0移到末尾
    Windows下Celery安装与下使用
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7920302.html
Copyright © 2020-2023  润新知