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

PHP 计算二叉树距离最长的两个节点间的距离

2012-09-30 23:35 375 查看
<?php
#查找二叉树距离最长的两个节点的距离,即相距边数最多的两个节点的边数
#解题思路:距离最长的两个节点有以下3中情况
#1.两个节点一个位于左子树,一个位于右子树,则最长距离是左右子树的深度相加
#2.两个节点都位于左子树,则最长距离是以左子树为根节点的左子树的两个左右子树的深度相加
#3.两个节点都位于右子树,则最长距离是以右子树为根节点的右子树的两个左右子树的深度相加

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

function get_max_long($root, &$depth) {
#此处结合二叉树的深度计算
if ($root == null) {
$depth = 0;
return 0;
}
#计算左右子树的最长距离,同时计算左右子树深度
$left_max = get_max_long($root->left, $ld);
$right_max = get_max_long($root->right, $rd);
$depth = max($ld, $rd) + 1;

// echo "{$ld}|{$rd}|{$left_max}|{$right_max}<br>";
return max($ld + $rd, max($left_max, $right_max));
}

#二叉树深度算法
#此处不用
function get_depth($root) {
if (!$root) {
return 0;
}

$ld = get_depth($root->left) + 1;
$rd = get_depth($root->right) + 1;

return max($ld, $rd);
}

$root = new Node();
$n1 = new Node();
$n2 = new Node();
$n11 = new Node();
$n12 = new Node();
$n13 = new Node();
$n14 = new Node();
$n15 = new Node();
$n21 = new Node();

$root->left = $n1;
$root->right = $n2;
$n1->left = $n11;
$n1->right = $n12;
$n11->left = $n13;
$n12->right = $n14;
$n13->left = $n15;
$n2->right = $n21;

$max = get_max_long($root, $depth);
echo $max;
?>



4 10 3 1 7 11 8 2

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