Leetcode PHP题解--D55 429. N-ary Tree Level Order Traversal
D55 429. N-ary Tree Level Order Traversal
题目链接
429. N-ary Tree Level Order Traversal
题目分析
按层遍历N叉树。
思路
以层数为键,塞入当前节点的值。
递归遍历即可。
最终代码
<?php /* // Definition for a Node. class Node { public $val; public $children; @param Integer $val @param list<Node> $children function __construct($val, $children) { $this->val = $val; $this->children = $children; } } */ class Solution { /** * @param Node $root * @return Integer[][] */ public $level = 0; public $values = []; function levelOrder($root) { if(is_null($root)){ return $this->values; } if(!isset($this->values[$this->level])){ $this->values[$this->level] = []; } $this->values[$this->level][] = $root->val; foreach($root->children as $child){ $this->level++; $this->levelOrder($child); $this->level--; } return $this->values; } }
若觉得本文章对你有用,欢迎用爱发电资助。
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23