Find the maximum distance of a node in a binary tree | Recursive

Source: Internet
Author: User

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;


 }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.