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);
A B # D # # C # # 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 } }