[英]PHP - Recursive binary tree
I've been having some fun with PHP trying to explore its potentials so I tried to see if I can implement a binary tree structure. 我一直在尝试使用PHP来探索其潜力,因此尝试查看是否可以实现二叉树结构。 Here is the code:
这是代码:
class Node{
public $leftNode;
public $rightNode;
public $value;
public function Node($value){
$this->value = $value;
}
}
class binTree{
public function inserter(Node $node, $value){
if($value < $node->value){
if($node->leftNode != null){
inserter($node, $value);
}
else{
$node->leftNode = new Node($value);
}
}
else if($value > $node->value){
if($node->rightNode != null){
inserter($node, $value);
}
else{
$node->rightNode = new Node($value);
}
}
}
}
Now for some reason, when I try to call the inserter function within itself (ie inserter ($node, $value), I get this error: Fatal error: Call to undefined function inserter().
So I tried referencing it via $this and even binTree:: with no luck. I get Fatal error: Using $this when not in object context
and Fatal error: Allowed memory size of 134217728 bytes exhausted
errors respectively. Can anyone explain what is happening? 现在由于某种原因,当我尝试在自身内部调用插入器函数(即插入器($ node,$ value)时,出现以下错误:
Fatal error: Call to undefined function inserter().
因此,我尝试通过$ this引用它甚至致命的binTree ::都没有运气。我遇到Fatal error: Using $this when not in object context
Fatal error: Allowed memory size of 134217728 bytes exhausted
分别Fatal error: Allowed memory size of 134217728 bytes exhausted
错误,谁能解释这是怎么回事?
i suspect your problem is the following: 我怀疑您的问题如下:
php constructor works this way PHP构造函数以这种方式工作
public function __construct ()
{
}
(vs C# like syntax that you are using) (与您正在使用的C#语法类似)
Try this: 尝试这个:
<?php
class Node{
public $leftNode;
public $rightNode;
public $value;
// changed the constructor name from "Node" to "__construct"
public function __construct($value){
$this->value = $value;
}
}
class binTree{
public function inserter(Node $node, $value){
if($value < $node->value){
if($node->leftNode != null){
// added "$this->"
$this->inserter($node, $value);
}
else{
$node->leftNode = new Node($value);
}
}
else if($value > $node->value){
if($node->rightNode != null){
// added "$this->"
$this->inserter($node, $value);
}
else{
$node->rightNode = new Node($value);
}
}
}
}
$binTree = new binTree();
$binTree->inserter(new Node('foo'), 'bar');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.