php 二叉樹

二叉樹:二叉樹是每個節點最多有兩個子樹的樹結構。通常子樹被稱作“左子樹”(left subtree)和“右子樹”(right subtree)。

以下是PHP二叉樹實例,請多多指點。

<?php

class treenode

{

public $data;

public $id;

public $left;

public $right;

public function treenode($id=null,$data=null)

{

$this->id=$id;

$this->data=$data;

$this->left=null;

$this->right=null;

}

public function displayss()

{

if($this->left!==null)

{

$this->left->displayss();

}

echo $this->data.'   ';

if($this->right!==null)

{

$this->right->displayss();

/* echo $this->data.'   ';

if($this->left!==null)

{

$this->left->displayss();

}

if($this->right!==null)

{

$this->right->displayss();

}  */

}

}

class binarytree

{

private $root;

function binarytree($id=null,$data=null)

{

$this->root=new treenode($id,$data);

}

public function com($old,$new)

{

if($old>$new)

{

return -1;

}

else if($old<=$new)

{

return 1;

}

}

public function addnode($id,$data)

{

if($this->root->data===null)

{

$this->root=new treenode($id,$data);

}

else if($this->root->data!==null)

{

$left=$this->root;

$right=$this->root;

$flag=$this->com($this->root->data,$data);

if($flag<0)

{

while($left->left!==null)

{

if($left->left->data===null)

{

break;

}

$left=$left->left;

}

$left->left=new treenode($id,$data);

}

elseif($flag>0)

{

while($right->right!==null)

{

if($right->right->data===null)

{

break;

}

$right=$right->right;

}

$right->right=new treenode($id,$data);

}

//$this->root=$this->root->addtnode($id,$name);

}

}

public function display()

{

$root=$this->root;

$root->displayss();

//$this->displayss($root);

//print_r($this);

/* if($this->left!==null)

{

$this->left->display();

}

echo $this->data.'   ';

if($this->right!==null)

{

$this->right->display();

} */

/* $root=$this->root;

while($root->left!==null)

{

echo 'left:--data:'.$root->left->data.' -->';

$root=$root->left;

}

echo '<br/><br/>';

$root=$this->root;

echo $this->root->data;

echo '<br/><br/>';

while($root->right!==null)

{

echo 'right:--data:'.$root->right->data.' -->';

$root=$root->right;

} */

}

}

$tree=new binarytree();

$tree->addnode(1,'111');

//print_r($tree);

//$tree->display();

echo '<br/>';

$tree->addnode(2,'110');

//print_r($tree);

$tree->addnode(3,'112');

//print_r($tree);

//echo '<br/>';

//exit;

$tree->addnode(4,'109');

$tree->addnode(5,'113');

$tree->addnode(6,'107');

$tree->addnode(7,'114');

$tree->addnode(8,'105');

$tree->display();

?>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章