The beauty of programming: finding the maximum distance between nodes in a binary tree

Source: Internet
Author: User

Question: If we regard a binary tree as a graph and the line between parent and child nodes is bidirectional, we would like to define "distance" as the number of edges between two nodes. Write a program to find the distance between the two nodes with the farthest distance in a binary tree.

Analysis: the analysis on the tree is clear, There are two possible conditions for calculating the maximum distance of a binary tree:

1. The path goes through the deepest node of the Left subtree, and then to the deepest node of the right subtree through the root node.

2. The path does not pass through the root node, but is the maximum distance path of the Left or right subtree.

However, the Code on the tree uses additional node fields. Here is my code. The idea is the same:

Struct binarytree {int value; binarytree * left; binarytree * right; binarytree (int x): Value (x), left (null), right (null ){}}; void findmaxlength (binarytree * root, Int & depth, Int & maxlength) {If (root = NULL) {depth =-1; maxlength = 0; return;} int ldepth, rdepth, lmaxlength, rmaxlength; findmaxlength (root-> left, ldepth, lmaxlength); findmaxlength (root-> right, rdepth, rmaxlength); depth = max (ldepth, rdepth) + 1; maxlength = max (lmaxlength, rmaxlength); maxlength = max (maxlength, ldepth + rdepth + 2);} int findmaxlength (binarytree * root) {int depth, maxlength; findmaxlength (root, depth, maxlength); Return maxlength ;}


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.