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.