美文网首页Leetcode题解-PHP版
Leetcode PHP题解--D43 589. N-ary T

Leetcode PHP题解--D43 589. N-ary T

作者: skys215 | 来源:发表于2019-04-26 04:38 被阅读0次

589. N-ary Tree Preorder Traversal

题目链接

589. N-ary Tree Preorder Traversal

题目分析

N维数组的先序遍历。

这题也不想多说什么了。是比较基础的题目了。

先序就是先根后子而已。没什么难的。

思路

在遍历子节点之前,先保存当前节点的信息。

最终代码

<?php
class Solution {
    public $val = [];
    function preorder($root) {
        if(!$root){
            return $this->val;
        }
        $this->val[] = $root->val;
        foreach($root->children as $child){
            $this->preorder($child);
        }
        return $this->val;
    }
}

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

相关文章

网友评论

    本文标题:Leetcode PHP题解--D43 589. N-ary T

    本文链接:https://www.haomeiwen.com/subject/wdsxnqtx.html