php 二叉树节点个数公式,写一PHP函数,计算二叉树中某一层的横向有多少个节点...

$sql_host = 'mysql-server-5.6';

$sql_user = 'admin';

$sql_pwd = '123456';

$sql_db = 'jtbc';

$conn = mysqli_connect($sql_host, $sql_user, $sql_pwd, $sql_db, 3306) or die("数据库链接失败");

mysqli_real_query($conn, "SET NAMES 'utf8'");

mysqli_select_db($conn, $sql_db) or die("没有" . $sql_db . "这个数据库,或是被管理员断开了链接,请稍后再试");

function _query($sql, $data = [], $isone = false)

{

global $conn;

$keys = [];

$values = [];

if (!empty($data) && !is_array($data)) {

$isone = $data;

} elseif (is_array($data)) {

foreach ($data as $k => $v) {

$keys[] = ":$k";

$values[] = '"' . addslashes($v) . '"';

}

}

$sql = trim(str_replace($keys, $values, $sql));

$res = mysqli_query($conn, $sql);

if (is_bool($res)) {

return $res;

}

switch (true) {

case preg_match( "/^INSERT\s/i", $sql ):

return @mysqli_insert_id($conn);

break;

case preg_match( "/^UPDATE\s/i", $sql ):

case preg_match( "/^DELETE\s/i", $sql ):

return $res;

break;

default:

if (mysqli_num_rows($res) == 1 && $isone) {

return mysqli_fetch_array($res, MYSQLI_ASSOC);

} else {

$arr = array();

while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {

$arr[] = $row;

}

return $arr;

}

break;

}

}

function getChild($key = '', $level = 1, $array = []){

if (empty($array)) {

$sql = 'select key_name,pid_name from test_6';

$array = _query($sql);

}

if (is_string($key)) $key = explode(',', $key);

for ($i = 1;$i<= $level;++$i) {

$keys = [];

foreach ($array as $k => $v) {

if (in_array($v['key_name'], $key)) {

$keys[] = $v['pid_name'];

}

}

$key = $keys;

}

return $key;

}

print_r(getChild('A',2));

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (1, 'A', ' ');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (2, 'B', ' ');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (3, 'C', ' ');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (4, 'A_1', 'A');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (5, 'A_2', 'A');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (6, 'A_1_1', 'A_1');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (7, 'A_1_2', 'A_1');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (8, 'A_1_3', 'A_1');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (9, 'A_2_1', 'A_2');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (10, 'A_2_2', 'A_2');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (11, 'A_1_2_1', 'A_1_2');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (12, 'A_1_2_2', 'A_1_2');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (13, 'A_1_3_1', 'A_1_3');

INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (14, 'A_1_3_2', 'A_1_3');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值