<?php class BinaryTree { public $data; public $left = null; public $right = null; public function __construct($element) { if (!empty($element)) { $this->data = $element; } } //先序遍历 public function pre($root) { if (null !== $root->data) { var_dump($root->data); if (null !== $root->left) { $this->pre($root->left); } if (null !== $root->right) { $this->pre($root->right); } } } //中序遍历 public function mid($root) { if (null !== $root->data) { if (null !== $root->left) { $this->mid($root->left); } var_dump($root->data); if (null !== $root->right) { $this->mid($root->right); } } } //后序遍历 public function postorder($root) { if (null !== $root->data) { if (null !== $root->left) { $this->postorder($root->left); } if (null !== $root->right) { $this->postorder($root->right); } var_dump($root->data); } } } //每个节点实例化对象,使其实例化的每个对象包含根节点,左节点,右节点属性 $a = new BinaryTree('A'); $b = new BinaryTree('B'); $c = new BinaryTree('C'); $d = new BinaryTree('D'); $e = new BinaryTree('E'); //构造二叉树 $a->left = $b; $a->right = $c; $c->left = $d; $d->right = $e; $a->pre($a);//前序遍历 echo "<br/>"; $a->mid($a);//中序遍历 echo "<br/>"; $a->postorder($a);//后序遍历 ?> 树:
A * * * * B C * * D * *E
结果:
//先序遍历的结果
string(1) "A" string(1) "B" string(1) "C" string(1) "D" string(1) "E"
//中序遍历的结果
string(1) "B" string(1) "A" string(1) "D" string(1) "E" string(1) "C"
//后序列遍历的结果
string(1) "B" string(1) "E" string(1) "D" string(1) "C" string(1) "A"