<?php
//构建节点类
class Node
{
private $keys;//节点值
private $left,$right;//左子节点、右子节点
//当前节点的值,以及左子节点、右子节点
public function __construct($key,$left,$right){
$this->keys=$key;
$this->left=$left;
$this->right=$right;
}
function getKey(){
return $this->keys;
}
function setKey($i){
$this->keys=$i;
}
function getLeft(){
return $this->left;
}
function setLeft($l){
$this->left=$l;
}
function getRight(){
return $this->right;
}
function setRight($r){
$this->right=$r;
}
}
class BinaryTree
{
/** 构造树 */
static function init(){
$a= new Node(1,null,null);
$b= new Node(2,null,$a);
$c= new Node(3,null,null);
$d= new Node(4,$b,$c);
$e= new Node(5,null,null);
$f= new Node(6,$e,null);
$g= new Node(7,null,$f);
$h= new Node(8,$d,$g);
return $h;
}
function visit($n){
echo $n->getKey()." ";
}
//前序遍历 根节点->左子节点->右子节点
function preorder($n){
if($n != null){
$this->visit($n);
$this->preorder($n->getLeft());
$this->preorder($n->getRight());
}
}
//中序遍历 左子节点->根节点->右子节点
function inorder($n){
if($n != null){
$this->inorder($n->getLeft());
$this->visit($n);
$this->inorder($n->getRight());
}
}
//后序遍历 左子节点->右子节点->根节点
function postorder($n){
if($n != null){
$this->postorder($n->getLeft());
$this->postorder($n->getRight());
$this->visit($n);
}
}
}
$c=new BinaryTree;
$root=BinaryTree::init();
//$c->visit($root);
echo "前序遍历\n";
$c->preorder($root);
echo "\n中序遍历\n";
$c->inorder($root);
echo "\n后序遍历\n";
$c->postorder($root);
递归实现二叉树遍历
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- title: 二叉树最大的权值和date: 2017-09-16 09:32:32category: 默认分类 本...
- 递归 比较简单,直接看代码即可. 非递归 先序遍历 申请一个栈,记为s1,将头结点压栈. 每次从栈顶弹出节点nod...
- 二叉树的遍历方式 先序遍历(Pre-Order Traversal)指先访问根,然后访问子树的遍历方式中序遍历(I...
- 二叉树的遍历口诀 前序:根左右 中序:左根右 后序:左右根 递归解法: 前序遍历: 中序遍历: 后序遍历: 递归解...