您的位置:首页 > 编程语言 > PHP开发

PHP 输入一棵二叉树和一个数字n,要求找出路径和为n的所有路径

2012-09-27 19:18 281 查看
<?php
#输入一棵二叉树和一个数字n,要求找出路径和为n的所有路径

class Node {
public $data = null;
public $parent = null;
public $left = null;
public $right = null;
}

#使用数组构造完全二叉树
function build_cbtree($a) {
$root = new Node();
$root->data = $a[0];

for ($i = 1; $i < count($a); $i++) {
$node = new Node();
$node->data = $a[$i];
insert_node($root, $node);
}

return $root;
}

#插入完全二叉树节点
function insert_node($root, $inode) {
#使用树的广度优先遍历顺序取出节点,直到找到第一个左右子节点没满的节点,将待插入节点插入节点左边或右边
$queue = array();
array_unshift($queue, $root);

while (!empty($queue)) {
$cnode = array_pop($queue);
if ($cnode->left == null) {
$cnode->left = $inode;
$inode->parent = $cnode;
return $root;
} else {
array_unshift($queue, $cnode->left);
}
if ($cnode->right == null) {
$cnode->right = $inode;
$inode->parent = $cnode;
return $root;
} else {
array_unshift($queue, $cnode->right);
}
}

return $root;
}

#树的广度优先遍历
function bf_traverse($root) {
$queue = array();
array_unshift($queue, $root);

while (!empty($queue)) {
$cnode = array_pop($queue);
echo $cnode->data . " ";
if ($cnode->left !== null) array_unshift($queue, $cnode->left);
if ($cnode->right !== null) array_unshift($queue, $cnode->right);
}

echo "<br>";
}

function get_paths($root, $paths, $sum) {
if ($root != null) {
$sum -= $root->data;
$paths[] = $root->data;

if ($sum > 0) {
#继续递归
#此处paths是传值调用,所以可以算出多条路径而互不影响
if ($root->left != null) get_paths($root->left, $paths, $sum);
if ($root->right != null) get_paths($root->right, $paths, $sum);
} else if ($sum == 0) {
#输出路径
foreach ($paths as $val) {
echo $val . " ";
}
echo "<br>";
}
}
}

$a = array(9, 8, 7, 6, 8, 4, 3, 2, 1);
$root = build_cbtree($a);
bf_traverse($root); #广度优先遍历
$b = array();
get_paths($root, $b, 25); #输出路径和为25的路径
?>



9 8 7 6 8 4 3 2 1
9 8 6 2
9 8 8

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐