本篇文章给大家带来的内容是关于php如何利用递归实现二叉树的创建,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1.利用递归的原理,只不过在原来打印结点的地方,改成了生成结点,给结点赋值的操作
if(ch=='#'){*t=null;}else{malloc();(*t)->data=ch;createfunc((*t)->lchild);createfunc((*t)->rchild);}
2.前序遍历:先访问根结点,前序遍历左子树,前序遍历右子树;中左右
3.将二叉树中每个结点的空指针引出一个虚结点,其值为特定值#,处理二叉树为原二叉树的扩展二叉树,扩展二叉树做到一个遍历序列确定一棵二叉树
<?phpclass 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);ab#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 }}
以上就是php如何利用递归实现二叉树的创建的详细内容。