在每个树行中找最大值
- https://leetcode.cn/problems/find-largest-value-in-each-tree-row/description/
描述
- 给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值
示例1
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2
输入: root = [1,2,3]
输出: [1,3]
提示
- 二叉树的节点个数的范围是 [0, 1 0 4 10^4 104]
- − 2 31 -2^{31} −231 <= Node.val <= 2 31 2^{31} 231 - 1
Typescript 版算法实现
1 ) 方案1:深度优先搜索
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function largestValues(root: TreeNode | null): number[] {
if (!root) return [];
const res = [];
const dfs = (res, root, curHeight) => {
if (curHeight === res.length) {
res.push(root.val);
} else {
res.splice(curHeight, 1, Math.max(res[curHeight], root.val));
}
if (root.left) {
dfs(res, root.left, curHeight + 1);
}
if (root.right) {
dfs(res, root.right, curHeight + 1);
}
}
dfs(res, root, 0);
return res;
};
2 ) 方案2:广度优先搜索
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function largestValues(root: TreeNode | null): number[] {
if (!root) return [];
const res = [];
const queue = [root];
while (queue.length) {
let len = queue.length;
let maxVal = -Number.MAX_VALUE;
while (len > 0) {
len--;
const t = queue.shift();
maxVal = Math.max(maxVal, t.val);
if (t.left) {
queue.push(t.left);
}
if (t.right) {
queue.push(t.right);
}
}
res.push(maxVal);
}
return res;
};