一:二叉树的遍历方式
- 前序遍历
- 若二叉树为空,则返回。
- 先访问根结点,然后前序遍历左子树,在前序遍历右子树。
- 中序遍历
- 若二叉树为空,则返回。
- 从子结点开始(并不是先访问根节点),中序遍历根节点的左子树,让后访问根节点,之后遍历右树
- 后序遍历
- 若二叉树为空,则返回。
- 从左到右,先叶子后结点的方式遍历左右子树,最后访问根结点
- PHP代码
-
<?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, " "; $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, " "; $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, " "; } } $t = new Tree(); $tree = $t->createTree(); $t->proOrder($tree); $t->middleOrder($tree); $t->backOrder($tree);
-