589. N叉树的前序遍历

地址:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/

/**
 * Definition for a Node.
 * class Node {
 *     public $val = null;
 *     public $children = null;
 *     function __construct($val = 0) {
 *         $this->val = $val;
 *         $this->children = array();
 *     }
 * }
 */

class Solution {
    /**
     * @param Node $root
     * @return integer[]
     */
    function preorder($root) {
        $res = [];
        $this->helper($root,$res);
        return $res;
    }

    function helper($root,&$res){
        if($root == null) return ;
        $res[]=$root->val;
        foreach($root->children as $children){
            $this->helper($children,$res);
        }
    }
}

  

posted @ 2020-05-22 11:14  花花妹子。  阅读(110)  评论(0编辑  收藏  举报