<?php
//構(gòu)建節(jié)點類
class Node
{
private $keys;//節(jié)點值
private $left,$right;//左子節(jié)點、右子節(jié)點
//當(dāng)前節(jié)點的值,以及左子節(jié)點、右子節(jié)點
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
{
/** 構(gòu)造樹 */
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()." ";
}
//前序遍歷 根節(jié)點->左子節(jié)點->右子節(jié)點
function preorder($n){
if($n != null){
$this->visit($n);
$this->preorder($n->getLeft());
$this->preorder($n->getRight());
}
}
//中序遍歷 左子節(jié)點->根節(jié)點->右子節(jié)點
function inorder($n){
if($n != null){
$this->inorder($n->getLeft());
$this->visit($n);
$this->inorder($n->getRight());
}
}
//后序遍歷 左子節(jié)點->右子節(jié)點->根節(jié)點
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);
遞歸實現(xiàn)二叉樹遍歷
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- title: 二叉樹最大的權(quán)值和date: 2017-09-16 09:32:32category: 默認(rèn)分類 本...
- 遞歸 比較簡單,直接看代碼即可. 非遞歸 先序遍歷 申請一個棧,記為s1,將頭結(jié)點壓棧. 每次從棧頂彈出節(jié)點nod...
- 二叉樹的遍歷方式 先序遍歷(Pre-Order Traversal)指先訪問根,然后訪問子樹的遍歷方式中序遍歷(I...
- 二叉樹的遍歷口訣 前序:根左右 中序:左根右 后序:左右根 遞歸解法: 前序遍歷: 中序遍歷: 后序遍歷: 遞歸解...
- 之前遞歸實現(xiàn)的方法可以看我前段時間的博客:http://www.itdecent.cn/p/1a81f7a9d10...