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);
    }
}
posted @ 2022-06-29 12:09  tros  阅读(54)  评论(0)    收藏  举报