duankeng2026 2012-07-15 21:03
浏览 32
已采纳

PHP二进制树插入问题

I'm playing around with writing a binary tree. Currently it's not going to be complete, or have each of it's levels full. I'm just trying to get the insert to work in it's most basic form (I'll mess around with re-ordering after that).

The Code

<?php

class Node {
    public $left = NULL;
    public $right = NULL;
    public $data = NULL;
}

class BinaryTree {
private $root = NULL;

public function insert($value, $node = false) {
    echo "VALUE: $value 
";
    if($node === false) {
        $node = $this->root;
    }

    if($node->data === NULL) {  // Always stuck here.
        $node->data = $value;
    } else {
        if($value <= $node->data) {
            $this->insert($value, $node->left);
        } else if($value >= $node->data) {
            $this->insert($value, $node->right);
        }
    }
}

}

$t = new BinaryTree();
$t->insert(7);
$t->insert(6);
$t->insert(1);

?>

The problem is that when I assign $node->value something, the $node object doesn't seem to be getting passed into the insert() function correctly. Because of this, it never gets passed the root.

Edit

@Joost pointed out I was missing a few steps. This led me to the following in my BinaryTree class:

public function __construct() {
    $this->root = new Node();
}
public function insert($value, $node = false) {
    if($node === false) {
        $node = $this->root;
    }

    if($node->data === NULL) {
        $node->data = $value;
    } else {
        if($value <= $node->data) {
            if(get_class($node->left) != "Node") {
                $node->left = new Node();
            }
            $this->insert($value, $node->left);
        } else if($value >= $node->data) {
            if(get_class($node->right) != "Node") {
                $node->rght = new Node();
            }
            $this->insert($value, $node->right);
        }
    }
}
  • 写回答

1条回答 默认 最新

  • douti9253 2012-07-15 21:08
    关注

    It doesn't work because you never initialize the root. You can use a root that is always empty (init it in __construct) or directly assign a new node to the root on insert, if the root wasn't already set.

    Actually, this problem is true for all nodes. You never create Node instances, neither do you set nodes as children of a parent.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备