二叉樹的建立PHP實現
1.利用遞迴的原理,只不過在原來列印結點的地方,改成了生成結點,給結點賦值的操作
if(ch=='#'){*T=NULL;}else{malloc();(*T)->data=ch;createFunc((*T)->lchild);createFunc((*T)->rchild);}
2.前序遍歷:先訪問根結點,前序遍歷左子樹,前序遍歷右子樹;中左右
3.將二叉樹中每個結點的空指標引出一個虛結點,其值為特定值#,處理二叉樹為原二叉樹的擴充套件二叉樹,擴充套件二叉樹做到一個遍歷序列確定一棵二叉樹
<?php
class
BinTree{
public
$data;
public
$left;
public
$right;
}
//前序遍歷生成二叉樹
function createBinTree(){
$handle=fopen(
"php://stdin"
,
"r"
);
$e=trim(fgets($handle));
if
($e==
"#"
){
$binTree=
null
;
}
else
{
$binTree=
new
BinTree();
$binTree->data=$e;
$binTree->left=createBinTree();
$binTree->right=createBinTree();
}
return
$binTree;
}
$tree=createBinTree();
var_dump($tree);
#
object
(BinTree)#1 (3) {
[
"data"
]=>
string
(1)
"A"
[
"left"
]=>
object
(BinTree)#2 (3) {
[
"data"
]=>
string
(1)
"B"
[
"left"
]=>
NULL
[
"right"
]=>
object
(BinTree)#3 (3) {
[
"data"
]=>
string
(1)
"D"
[
"left"
]=>
NULL
[
"right"
]=>
NULL
}
}
[
"right"
]=>
object
(BinTree)#4 (3) {
[
"data"
]=>
string
(1)
"C"
[
"left"
]=>
NULL
[
"right"
]=>
NULL
}
}