LeetCode LCR 044. 在每个树行中找最大值

题目描述

LCR 044. 在每个树行中找最大值

思路分析

解法一:层序遍历(推荐)

核心思路

  • 按层 BFS 遍历二叉树。
  • 每一层扫描节点值,取最大值加入结果。
  • 队列保存下一层节点。

复杂度分析

  • 时间复杂度:O(n),其中 n 表示节点数量。
  • 空间复杂度:O(w),其中 w 表示树的最大宽度。
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            int max = Integer.MIN_VALUE;

            for (int i = 0; i < size; 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;
    }
}
func largestValues(root *TreeNode) []int {
	res := make([]int, 0)
	if root == nil {
		return res
	}

	queue := []*TreeNode{root}
	for head := 0; head < len(queue); {
		size := len(queue) - head
		maxVal := -1 << 31

		for i := 0; i < size; i++ {
			node := queue[head]
			head++

			if node.Val > maxVal {
				maxVal = node.Val
			}

			if node.Left != nil {
				queue = append(queue, node.Left)
			}
			if node.Right != nil {
				queue = append(queue, node.Right)
			}
		}

		res = append(res, maxVal)
	}

	return res
}

解法二:DFS 记录层最大值

核心思路

  • DFS 遍历时记录深度。
  • 若该层尚无记录,直接加入;否则更新该层最大值。
  • 递归遍历左右子树。

复杂度分析

  • 时间复杂度:O(n),其中 n 表示节点数量。
  • 空间复杂度:O(h),其中 h 表示树高度。
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        dfs(root, 0, res);
        return res;
    }

    private void dfs(TreeNode node, int depth, List<Integer> res) {
        if (node == null) {
            return;
        }

        if (depth == res.size()) {
            res.add(node.val);
        } else {
            res.set(depth, Math.max(res.get(depth), node.val));
        }

        dfs(node.left, depth + 1, res);
        dfs(node.right, depth + 1, res);
    }
}
func largestValues(root *TreeNode) []int {
	res := make([]int, 0)
	dfsMax(root, 0, &res)
	return res
}

func dfsMax(node *TreeNode, depth int, res *[]int) {
	if node == nil {
		return
	}

	if depth == len(*res) {
		*res = append(*res, node.Val)
	} else if node.Val > (*res)[depth] {
		(*res)[depth] = node.Val
	}

	dfsMax(node.Left, depth+1, res)
	dfsMax(node.Right, depth+1, res)
}

相似题目

题目 难度 考察点
102. 二叉树的层序遍历 中等 BFS
637. 二叉树的层平均值 简单 BFS
103. 二叉树的锯齿形层序遍历 中等 BFS
199. 二叉树的右视图 中等 BFS
1161. 最大层内元素和 中等 BFS
本文作者:
本文链接: https://hgnulb.github.io/blog/2026/59837249
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!