php 二叉树以及N叉树递归遍历模版

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */

function preorderTraversal($root) {
    $res = [];
    if ($root == null) return $res;

    $this->task($root, $res);

    return $res;
}
//前序遍历
public function task($node, &$res)
{
    if ($node == null) return $res;

    $res[] = $node->val;
    $this->task($node->left, $res);
    $this->task($node->right, $res);
}
//中序遍历
public function task($node, &$res)
{
    if ($node == null) return $res;

    $this->task($node->left, $res);
    $res[] = $node->val;
  
    $this->task($node->right, $res);
}
//后序遍历
public function task($node, &$res)
{
    if ($node == null) return $res;

    $this->task($node->left, $res);
   
    $this->task($node->right, $res);
     $res[] = $node->val;
  
}
/**
 * Definition for a Node.
 * class Node {
 *     public $val = null;
 *     public $children = null;
 *     function __construct($val = 0) {
 *         $this->val = $val;
 *         $this->children = array();
 *     }
 * }
 */
//N叉树前序遍历
public function task($node, &$res)
{
    if ($node == null) return $res;

    $res[] = $node->val;
    foreach($node->children as $val){
        $this->task($val, $res);
    }
            
}
//N叉树后序遍历
public function task($node, &$res)
{
    if ($node == null) return $res;

   
    foreach($node->children as $val){
        $this->task($val, $res);
    }
    $res[] = $node->val;
            
}

 

你可能感兴趣的:(PHP,数据结构与算法)