点击(此处)折叠或打开
- class Node {
- public $left = null;
- public $right = null;
- public $data = '';
- public function __construct($data)
- {
- $this->data = $data;
- }
- }
点击(此处)折叠或打开
- public function actionTree() {
- //根节点
- $root = new Node('10');
- $b = new Node('6');
- $c = new Node('11');
- $d = new Node('4');
- $e = new Node('7');
- $f = new Node('13');
- $root->left = $b;
- $root->right = $c;
- $b->left = $d;
- $b->right = $e;
- $c->right = $f;
- $this->preOrder($root);
- $this->inOrder($root);
- $this->postOrder($root);
- }
- //前序遍历 根 左 右
- private function preOrder($tree){
- if($tree === null) {
- return;
- }
- var_dump($tree->data);
- $this->preOrder($tree->left);
- $this->preOrder($tree->right);
- }
- //左 根 右
- private function inOrder($tree) {
- if($tree === null) {
- return;
- }
- $this->inOrder($tree->left);
- var_dump($tree->data);
- $this->inOrder($tree->right);
- }
- //右 根 左
- private function postOrder($tree) {
- if($tree === null) {
- return;
- }
- $this->postOrder($tree->right);
- var_dump($tree->data);
- $this->postOrder($tree->left);
- }