标签:his 遍历 建立 style node create func 二叉树的遍历 roo
一:二叉树的遍历方式
<?php /** * * 二叉树遍历 * 已知 前序/后序 遍历方式,是不能确定一颗二叉树树 */ class Node { public $lChild; // 左结点 public $rChild; // 右结点 public $data; // 值 } class Tree { /** * 建立二叉树 * 1 * / * 2 3 * /\ / * 4 5 6 7 */ public function createTree() { $head = new Node(); $head->data = 1; $head->lChild = new Node(); $head->lChild->data = 2; $head->lChild->lChild = new Node(); $head->lChild->lChild->data = 4; $head->lChild->rChild = new Node(); $head->lChild->rChild->data = 5; $head->rChild = new Node(); $head->rChild->data = 3; $head->rChild->lChild = new Node(); $head->rChild->lChild->data = 6; $head->rChild->rChild = new Node(); $head->rChild->rChild->data = 7; return $head; } /** * 前序遍历 * 遍历顺序为 1-2-3-4-5-6 */ public function proOrder($tree) { if (!$tree->data) return false; echo $tree->data, "\n"; $this->proOrder($tree->lChild); $this->proOrder($tree->rChild); } /** * 中序遍历 * 遍历顺序为 4-2-5-1-6-3-7 */ public function middleOrder($tree) { if (!$tree->data) return false; $this->middleOrder($tree->lChild); echo $tree->data, "\n"; $this->middleOrder($tree->rChild); } /** * 后序遍历 * 遍历顺序为 4-5-2-6-7-3-1 */ public function backOrder($tree) { if (!$tree->data) return false; $this->backOrder($tree->lChild); $this->backOrder($tree->rChild); echo $tree->data, "\n"; } } $t = new Tree(); $tree = $t->createTree(); $t->proOrder($tree); $t->middleOrder($tree); $t->backOrder($tree);
标签:his 遍历 建立 style node create func 二叉树的遍历 roo
原文地址:https://www.cnblogs.com/25-lH/p/10561123.html