Leetcode PHP题解--D44 590. N-ary Tree Postorder Traversal

N-ary树后序遍历解析
本文详细解析了N-ary树的后序遍历算法,通过递归方式先遍历所有子节点,最后访问根节点,实现对N-ary树的完整遍历。代码采用PHP实现,清晰展示了算法的逻辑。

590. N-ary Tree Postorder Traversal

题目链接

590. N-ary Tree Postorder Traversal

题目分析

后序遍历,这题也是比较基础的题目了。

思路

先遍历子节点,再遍历根节点。

最终代码

<?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 {
    public $val = [];
    /**
     * @param Node $root
     * @return Integer[]
     */
    function postorder($root) {
        if(!$root){
            return $this->val;
        }
        foreach($root->children as $child){
            $this->postorder($child);
        }
        $this->val[] = $root->val;
        return $this->val;
    }
}

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

转载于:https://my.oschina.net/u/2246923/blog/3043069

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值