网站首页 > 知识剖析 正文
年纪确实大了一个 广度优先遍历写了十几分钟。记录一下思路。
题目:
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:
输入: root = [1,2,3]
输出: [1,3]
提示:
二叉树的节点个数的范围是 [0,104]
-231 <= Node.val <= 231 - 1
其实一个队列也能完成,但是个人认为2个队列虽然牺牲了空间复杂度,更容易理解。
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution {
private $queue1 = []; // 当前层的队列
private $queue2 = []; // 下一层的队列
private $rs = [];
/**
* @param TreeNode $root
* @return Integer[]
*/
function largestValues($root) {
// 如果根节点不为空,则根节点放到结果中。
if ($root != null) {
$this->queue1[] = $root;
}
$max = PHP_INT_MIN; // 当前层最大值 默认值是最小负数
while (count($this->queue1) > 0) {
// 从当前层获取节点。
$curNode = array_pop($this->queue1);
// 将当前节点的 左右节点扔到队列2里去
if ($curNode->left != null) {
$this->queue2[] = $curNode->left;
}
if ($curNode->right != null) {
$this->queue2[] = $curNode->right;
}
// 比较当前层的最大值。
$max = max($max, $curNode->val);
// 1.将当前层的最大值塞入结果队列。
// 2. 重置下一行的max为最小负数。
// 3. 将下一层的队列 变成当前层。
if (empty($this->queue1)) {
$this->rs[] = $max;
$max = PHP_INT_MIN;
$this->queue1 = $this->queue2;
$this->queue2 = [];
}
}
return $this->rs;
}
}
- 上一篇: PHP入门读书笔记(十四):使用数组函数
- 下一篇: PHP 数组与数据结构 php数据结构和算法
猜你喜欢
- 2024-11-14 vue uniapp中数组的操作方法 uniapp vuecli
- 2024-11-14 JavaScript Array 对象 javascript array splice
- 2024-11-14 js中数组方法全解 js数组常用的方法
- 2024-11-14 TS类型体操,看懂你就能玩转TS了 tststs
- 2024-11-14 JS原生对数组操作的常用方法 原生js操作dom
- 2024-11-14 PHP8中获取并删除数组中最后一个元素-PHP8知识详解
- 2024-11-14 mysqli_fetch_assoc常用的函数汇总
- 2024-11-14 碎片时间学编程「203]:根据功能对数组元素进行分组
- 2024-11-14 PHP是如何实现多线程编程的? php是如何实现多线程编程的
- 2024-11-14 PHP8的数组-PHP8知识详解 php8的jit
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)