"Algorithm topic" Finding the maximum distance of a node in a binary tree

Source: Internet
Author: User

If we think of the two-fork tree as a graph, and the connection between the parent and child nodes is considered bidirectional, we'll define "example" as the number of edges between the two nodes. Write a program to find the distance between the two nodes farthest apart in a binary tree (the beauty of programming 3.8)

Idea: If two nodes are farthest apart, it must be two leaf nodes, or a leaf node to its root node.

According to the distance between the two nodes must be the leaf node of the law, we can further discuss.

For any one node, with that node as the root, assuming that the root Youk a child node, then the path between the two nodes at the farthest distance between U and V is in two cases with the root node.

1. If the path passes through root, then you and V belong to different subtrees, and they are the nodes farthest from the tree to the root node, otherwise they are contradictory to their furthest distance.

2. If the path does not go through root, then they must belong to one of the K subtrees of the root. And they are also the two vertices farthest apart from the subtree.

structNode {node*Pleft; Node*Pright; intmax_depth;//Maximum Depth    intMax_distance;//Maximum Distance};structResult {intmax_depth; intmax_distance;};intMax (intAintb) {returna > B?a:b;} Result getmaxdistance (Node*proot) {    if(Proot = =NULL) {Result Empty= {0, -1};//maximizes the initialization to 1 because the caller wants to add 1 to it and then 0        returnempty; } Result LHS= Getmaxdistance (proot->pleft); Result RHS= Getmaxdistance (proot->pright);    result result; Result.max_depth= Max (lhs.max_depth +1, Rhs.max_depth +1); Result.max_distance= Max (max (lhs.max_distance, rhs.max_distance), lhs.max_depth + rhs.max_depth +2); returnresult;}

"Algorithm topic" Finding the maximum distance of a node in a binary tree

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.