515.在每个树行中找最大值

博客 分享
0 157
张三
张三 2022-07-02 16:01:19
悬赏:0 积分 收藏

515. 在每个树行中找最大值

515. 在每个树行中找最大值

给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。

示例1:

输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:

输入: root = [1,2,3]
输出: [1,3]

二叉树的搜索无非就是DFS或者BFS,通常DFS用的比较多,这道题两个方法都可以,但是题目要求找到每一层的最大值,所以个人觉得层序遍历比较清晰,当然深度优先使用一个变量记录当前层数也可以完成这个任务。

DFS
递归遍历二叉树,每次进入下一层使层数加一,维护当前层数的最大值。

BFS
广度优先搜索,按模板写就行,在一层内维护一个最大值,遍历完一层后加入结果。
贴一个BFS:

class Solution {    public List<Integer> largestValues(TreeNode root) {        if (root == null) {            return new ArrayList();        }        Deque<TreeNode> queue = new LinkedList<>();        queue.offer(root);        List<Integer> res = new ArrayList<>();        while (!queue.isEmpty()) {            int len = queue.size();            int max = Integer.MIN_VALUE;            for (int i = 0; i < len; i++) {                TreeNode node = queue.poll();                max = Math.max(max, node.val);                if (node.left != null) {                    queue.offer(node.left);                }                if (node.right != null) {                    queue.offer(node.right);                }            }            res.add(max);        }        return res;    }}

原文:https://leetcode.cn/problems/find-largest-value-in-each-tree-row/solution/by-nice-hermann9a2-nnrq/

posted @ 2022-07-02 15:26 良人呐 阅读(8) 评论(0) 编辑 收藏 举报
回帖
    张三

    张三 (王者 段位)

    821 积分 (2)粉丝 (41)源码

     

    温馨提示

    亦奇源码

    最新会员