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

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

内容简介:按层遍历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;
    }
}

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


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

查看所有标签

猜你喜欢:

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

The Art of Computer Programming, Volumes 1-3 Boxed Set

The Art of Computer Programming, Volumes 1-3 Boxed Set

Donald E. Knuth / Addison-Wesley Professional / 1998-10-15 / USD 199.99

This multivolume work is widely recognized as the definitive description of classical computer science. The first three volumes have for decades been an invaluable resource in programming theory and p......一起来看看 《The Art of Computer Programming, Volumes 1-3 Boxed Set》 这本书的介绍吧!

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

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试