Title: Finding the maximum distance of a node in a binary tree
Analysis: The furthest two points must be on a subtree with a node A as its root, and the path between them must pass through the root node A of that subtree. Therefore, the original problem is equivalent to "calculating the height and maximum of the Saozi right subtree for each node"
Reference: http://www.cppblog.com/flyinghearts/archive/2010/08/16/123543.html
PHP Implementation:
<?php/** * @author: Wusuopubupt * @date: 2013-10-25 * * Get the max distance between 2 nodes of a binary tree *
*/$max _distance = 0; $root = Array ("Data" =>1, "left" =>array ("Data" =>2, ' left ' =>array ("Data" =>4, "right" =>arra Y ("Data" =>7)), "Right" =>array ("Data" =>3, ' left ' =>array ("Data" =>5), "right" =&
Gt;array ("Data" =>6));
Print_r ($root);
$len = Tree_height ($root, $max _distance);
Var_dump ($max _distance);
function Make_node ($left, $right, $data) {$node = Array ("Left" + = $left, "right" + = $right, "data" = $data);
return $node;
};
function Tree_height ($root,& $max _distance) {if ($root = = NULL) return-1;
$left _height = 0;
$right _height = 0;
if (Isset ($root [' left '])) {$left _height = tree_height ($root [' left '], $max _distance) + 1;
} if (Isset ($root [' right ')]) {$right _height = tree_height ($root [' right '], $max _distance) + 1; } $distance = $left _height + $right _height;
if ($max _distance < $distance) {$max _distance = $distance; } return $left _height > $right _height?
$left _height: $right _height;
}