Leetcode PHP题解--D55 429. N-ary Tree Level Order Traversal

栏目: PHP · 发布时间: 6年前

内容简介:按层遍历N叉树。以层数为键,塞入当前节点的值。

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;
    }
}

若觉得本文章对你有用,欢迎用 爱发电 资助。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Graph Algorithms

Graph Algorithms

Shimon Even / Cambridge University Press / 2011-9-19 / USD 32.99

Shimon Even's Graph Algorithms, published in 1979, was a seminal introductory book on algorithms read by everyone engaged in the field. This thoroughly revised second edition, with a foreword by Richa......一起来看看 《Graph Algorithms》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码