<?php
class TreeNode
{
public function __construct($val)
{
$this->val = $val;
$this->left = null;
$this->right = null;
}
}
#前序遍历 根 左 右
function preOrder($root)
{
echo $root->val . PHP_EOL;
if ($root == null) {
return [];
}
return array_merge([$root->val], preOrder($root->left), preOrder($root->right));
}
$tn1 = new TreeNode(1);
$tn2 = new TreeNode(2);
$tn3 = new TreeNode(3);
$tn1->left = $tn2;
$tn1->right = $tn3;
$res = preOrder($tn1);
print_r($res);
算法 - php - 二叉树遍历
最新推荐文章于 2021-03-29 10:37:55 发布