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

D44 590. N-ary Tree Postorder Traversal

題目連接

590. N-ary Tree Postorder Traversalphp

題目分析

後序遍歷,這題也是比較基礎的題目了。post

思路

先遍歷子節點,再遍歷根節點。this

最終代碼

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

若以爲本文章對你有用,歡迎用愛發電資助。.net

相關文章
相關標籤/搜索