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
相关文章推荐
- php计算两个经纬度地点之间的距离
- 求二叉树中最远的两个节点的距离
- 二叉树中相距最远的两个节点之间的距离
- 二叉树中相距最远的两个节点之间的距离
- 二叉树系列——二叉树的最大距离(即相距最远的两个叶子节点,编程之美,百度面试题)
- ODOA(2) 求二叉树中两个节点的最大距离(C语言实现)
- 求二叉树中节点的最大距离 即二叉树中相距最远的两个节点之间的距离
- 求二叉树中两个节点最远的距离
- 求一个二叉树中任意两个节点间的最大距离
- 计算二叉树中节点的最大距离
- 二叉树中相距最远的两个节点之间的距离
- PHP计算两个经纬点之间的距离
- 计算二叉树的任意两节点的最远距离。
- PHP 计算两个时间的距离
- 计算两个GPS经纬度坐标之间的距离 PHP
- 求一个二叉树中任意两个节点间的最大距离,两个节点的距离的定义是这两个节点间边的个数,比如某个孩子节点和父节点间的距离是1,和相邻兄弟节点间的距离是2,
- 求一个二叉树中距离最远的两个节点
- 二叉树系列---求二叉树中两个节点之间的最大距离
- 【学习点滴-数据结构-二叉树】求二叉树两个节点之间的最大距离
- PHP / mysql 根据两个经纬度坐标计算距离