Beauty of programming-3.8-maximum distance for Binary Tree nodes

Source: Internet
Author: User

1. Brief Introduction

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 oneProgramCalculate the distance between the two nodes with the farthest distance in a binary tree.

2. Ideas

It is relatively easy to find the largest distance, and recursion is similar. For each subtree, either the maximum distance is in the left subtree of the root, or in the right subtree of the root, or through the root.
Height (null) = 0, height (node) = max {height (node-> left) + 1, height (node-> right) + 1 }.
Max (null) = 0; max (node) = max {max (node-> left), max (node-> right), height (node-> left) + height (node-> right )},
In the end, max (Root) is what you want.
For non-recursive methods, this question should be the post-order method. For details, see the implementation in the pre-order-middle-back-non-recursive-implementation. Add the calculation height and MaxCodeYou can.

3. Reference

The beauty of programming: 3.8. Calculate the maximum distance between nodes 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.