<?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)系作者
- 文/潘曉璐 我一進店門娜亿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來役纹,“玉大人,你說我怎么就攤上這事暇唾〈俾觯” “怎么了?”我有些...
- 文/不壞的土叔 我叫張陵策州,是天一觀的道長瘸味。 經(jīng)常有香客問我,道長够挂,這世上最難降的妖魔是什么旁仿? 我笑而不...
- 正文 為了忘掉前任,我火速辦了婚禮孽糖,結(jié)果婚禮上枯冈,老公的妹妹穿的比我還像新娘。我一直安慰自己办悟,他們只是感情好尘奏,可當(dāng)我...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著病蛉,像睡著了一般炫加。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上铺然,一...
- 文/蒼蘭香墨 我猛地睜開眼农尖,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了苛蒲?” 一聲冷哼從身側(cè)響起卤橄,我...
- 正文 年R本政府宣布原环,位于F島的核電站,受9級特大地震影響处窥,放射性物質(zhì)發(fā)生泄漏嘱吗。R本人自食惡果不足惜,卻給世界環(huán)境...
- 文/蒙蒙 一滔驾、第九天 我趴在偏房一處隱蔽的房頂上張望谒麦。 院中可真熱鬧,春花似錦哆致、人聲如沸绕德。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽迁匠。三九已至,卻和暖如春驹溃,著一層夾襖步出監(jiā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.reibang.com/p/1a81f7a9d10...