11.3 树的遍历:LDR,LRD,VLR 相关代码 基础定义介绍见这里 VLR:前序遍历 LDR:中序遍历 LRD:后序遍历 <?php class Leaf{ public $leftLeaf; public $rightLeaf; public $label; public function __construct($label) { $this->label=$label; } } /** * 前序遍历 * @param $leaf Leaf * @param string $result * @return bool */ function VLR($leaf,&$result){ if (!$leaf){ return false; } $result.=$leaf->label; VLR($leaf->leftLeaf,$result); VLR($leaf->rightLeaf,$result); } /** * 中序遍历 * @param $leaf Leaf * @param $result string * @return bool */ function LDR($leaf,&$result){ if (!$leaf){ return false; } if ($leaf->leftLeaf){ LDR($leaf->leftLeaf,$result); } $result.=$leaf->label; LDR($leaf->rightLeaf,$result); } /** * 后续遍历 * @param $leaf Leaf * @param $result string * @return bool */ function LRD($leaf,&$result){ if (!$leaf){ return false; } LRD($leaf->leftLeaf,$result); LRD($leaf->rightLeaf,$result); $result.=$leaf