二叉树遍历
Posted zh718594493
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树遍历相关的知识,希望对你有一定的参考价值。
class Node { public $data; public $left; public $right; public function __construct($data){ $this->data=$data; } } class CreateTree{ public $tree; //二叉树进行插入 public function insert($data){ if(!$this->tree){ $this->tree = new Node($data); return ; } $p = $this->tree; while($p){ if($data < $p->data ){ if(!$p->left){ $p->left = new Node($data); return ; } $p= $p->left; }elseif($data > $p->data){ if(!$p->right){ $p->right = new Node($data); return; } $p=$p->right; } } }
//前序遍历 public function preOrder(){ $stack = array(); $root = $this->tree; array_push($stack,$root); while(!empty($stack)){ $p = array_pop($stack); echo $p->data.php_EOL; if($p->right != null){ array_push($stack,$p->right); } if($p->left != null){ array_push($stack,$p->left); } } } } $objcreate = new CreateTree(); $arr = array(33,16,50,13,18,34,58,15,17,25,51,66,19,27,55); foreach ($arr as $key => $value) { $objcreate->insert($value); } $objcreate->preOrder();
以上是关于二叉树遍历的主要内容,如果未能解决你的问题,请参考以下文章