102. 二叉树的层序遍历(levelOrder)
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
查看代码
/***
执行用时:8 ms, 在所有 PHP 提交中击败了61.90% 的用户
内存消耗:19.6 MB, 在所有 PHP 提交中击败了26.67% 的用户
通过测试用例:34 / 34
*/
/**
* 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 {
/**
* @param TreeNode $root
* @return Integer[][]
*/
function levelOrder($root) {
if(null == $root)
return [];
$list = [];
$this->check($root, 0, $list);
return $list;
}
function check($node,$n,&$list){
$list[$n][] = $node->val;
if(null != $node->left)
$this->check($node->left, $n+1, $list);
if(null != $node->right)
$this->check($node->right, $n+1, $list);
}
}
本文来自博客园,作者:tros,转载请注明原文链接:https://www.cnblogs.com/tros/p/16422844.html

浙公网安备 33010602011771号