leetcode-590、589题

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值