23. Binary tree - find the maximum distance between tree nodes

problem definition

If we regard the binary tree as a graph, the connection between the parent and child nodes is regarded as bidirectional, let us define " distance " as the number of edges between two nodes. Write a program to find the distance between the two furthest nodes in a binary tree.

solution in the book

The analysis of the problem is clear in the book, and I try to recap it briefly in my own way.

There are two cases for calculating the maximum distance of a binary tree :

Case A: The path goes through the deepest node of         the left subtree, through the root node, and then to the deepest node in the right subtree.

·         Case B: The path does not pass through the root node, but the maximum distance path of the left subtree or the right subtree, whichever is greater.

It is only necessary to calculate the path distance of these two cases, and take the larger one, which is the maximum distance of the binary tree.

package facehandjava.tree;

public class MaxDistance {
   
public static Node init() { // Note that it must be created in reverse order, first create child nodes, and then build up in reverse order, because non-leaf nodes will use the following nodes, and the initialization is by Sequentially initialized, if not built in reverse order, an error will be reported
       
Node J = new Node( 8 , null , null );
        Node H =
new Node( 4 , null , null );
        Node G =
new Node( 2 , null , null );
        Node F =
new Node( 7 , null , J);
        Node E =
new Node(5, H, null);
        Node D =
new Node(1, null, G);
        Node C =
new Node(9, F, null);
        Node B =
new Node(3, D, E);
        Node A =
new Node(6, B, C);
       
return A;   //返回根节点
   
}

   
public static void main(String[] args) {
        Node root = MaxDistance.init();
        System.
out.println( " Maximum distance of tree leaf node" );
       
int L = MaxDistance (root); System.out
        .println
(L);     } private static Integer max = 0 ; public static int MaxDistance (Node node) { if (node == null ) { return max ;         } int l = DepthTree (node.getLeftNode()); int r = DepthTree (node.getRightNode()); int d = l+ r + 1 ; max = max


   

   

       

           


       

       

       

       
> d ? max : d;
        MaxDistance(node.getLeftNode());
        MaxDistance(node.getRightNode());
       
return max;
    }

   
public static int DepthTree(Node node) {
       
if (node== null) {
           
return 0;
        }
       
int l = DepthTree(node.getLeftNode());
       
int r = DepthTree(node.getRightNode());
       
int d = l> r ? l : r;
       
return d+1;
    }

}

 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325541886&siteId=291194637