https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/submissions/
在构造数据上花费了功夫。
<?php
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[]
*/
public function postorder($root) {
$result = [];
$this->getData($root, $result);
//后续遍历,最后把根节点值放入
$result[] = $root->val;
return $result;
}
/**
* 递归遍历,终止条件为:root为空,其实就是children为空
*/
public function getData($root,&$result){
if($root == null) return;
foreach($root->children as $children)
{
//该地方一定要把children传递过去,很多人会传root,造成死循环
$this->getData($children,$result);
$result[] = $children->val;
}
}
}
//构造数据一定要有想象空间,所谓的n叉树其实就是递归。
$a = new Node();
$a->val = 1;
$e = new Node();
$e->val = 5;
$f = new Node();
$f->val = 6;
$b = new Node();
$b->val = 3;
$b->children = [$e,$f];
$c = new Node();
$c->val = 2;
$d = new Node();
$d->val = 4;
$a->children = [$b,$c,$d];
$s = new Solution();
$s->postorder($a);
?>
前序遍历
https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/submissions/
<?php
class Node{
public $val = null;
public $children = null;
function __construct($val = 0){
$this->val = $val;
$this->children = array();
}
}
class Solution {
function preorder($root)
{
$result = [];
$result[] = $root->val;
$this->getPreData($root,$result);
return $result;
}
function getPreData($root,&$result){
if($root == null) return;
foreach($root->children as $children)
{
$result[] = $children->val;
$this->getPreData($children,$result);
}
}
}
//构造数据一定要有想象空间,所谓的n叉树其实就是递归。
$a = new Node();
$a->val = 1;
$e = new Node();
$e->val = 5;
$f = new Node();
$f->val = 6;
$b = new Node();
$b->val = 3;
$b->children = [$e,$f];
$c = new Node();
$c->val = 2;
$d = new Node();
$d->val = 4;
$a->children = [$b,$c,$d];
$s = new Solution();
print_r($s->preorder($a));
?>