二叉树查找算法(php)

/**
 * 二叉树查找算法
 * @author liuyanqiang
 */
class node
{

    public $data;

    public $left;

    public $right;

    public $point; // 位置
}

/**
 * 查找元素
 * @param node $t
 * @param int $x
 * @return NULL
 */
function BSTsearch($t, $x)
{
    if ($t != null) {
        $p = $t;
        while ($p != null) {
            if ($p->data == $x)
                return $p->point;
            elseif ($x < $p->data)
                $p = $p->left;
            else
               $p = $p->right;
        }
    }
    return null;
}
/**
 * 二叉排序树的插入操作
 * @param node $t
 * @param int $x
 * @param int $nn
 * @return number
 */
function BSTInsert(&$t, $x, $nn)
{
    $cur = $t;
    while ($cur != null) {
        if ($cur->data == $x) {
            return 0;
        }
        $parent = $cur;
        if ($x < $cur->data) {
            $cur = $cur->left;
        } else {
            $cur = $cur->right;
        }
    }

    $p = new node();
    $p->data = $x;
    $p->left = null;
    $p->right = null;
    $p->point = $nn;
    if (! $parent) {
        $t = $p;
    } elseif ($x < $parent->data) {
        $parent->left = $p;
    } else {
        $parent->right = $p;
    }

    return 1;
}
/**
 * 中序遍历二叉排序树
 * @param node $t
 */
function InorderTraverse($t)
{
    if ($t) {
        InorderTraverse($t->left);
        echo $t->data . "  ";
        InorderTraverse($t->right);
    }
}

$table = [ 55,33,44,100,99,77, 88,22,11];
$n = count($table);
$t = new node();
for ($i = 0; $i < $n; $i ++) {
    BSTInsert($t, $table[$i], $i);
}
InorderTraverse($t);
$p = BSTsearch($t, 99);
print_r($p);

你可能感兴趣的:(php)