上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
}
};
php 解法, 执行用时: 8 ms, 内存消耗: 15.9 MB, 提交时间: 2021-05-10 16:56:30
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @return Integer[][]
*/
function levelOrder($root) {
if ( $root == null ) return [];
$res = [];
$queue = [$root];
while ( !empty($queue) ) {
$tmp = [];
$cnt = count($queue);
for ( $i = 0; $i < $cnt; $i++ ) {
$node = array_shift($queue);
$tmp[] = $node->val;
if ( $node->left ) $queue[] = $node->left;
if ( $node->right ) $queue[] = $node->right;
}
$res[] = $tmp;
}
return $res;
}
}