标签:else foreach div creat lse objc UNC root while
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();
标签:else foreach div creat lse objc UNC root while
原文地址:https://www.cnblogs.com/zh718594493/p/12093302.html