The maximum distance problem between two fork tree nodes public class maxdistanceoftree{//two fork tree node definition public static class node{public int value;
Public Node left;
public Node right;
public Node (int data) {this.value=data; }//Get the maximum distance between two nodes of a binary tree the length of/** maximum subtree is: Zoozi tree maximum length + right subtree maximum length +1/public static int getmaxdistance (Node head) {int []num=new int[1];
The length of the node used to record each subtree//system.out.println (num[0]);
Return Posorder (Head,num);
}//The sequence of the binary tree traverses the public static int Posorder (Node head,int []num) {if (head==null) {num[0]=0;
return 0;
///Recursive call Zoozi tree int lmax=posorder (head.left,num);
int maxfromleft=num[0];
System.out.println (Maxfromleft);
Recursive call right subtree int rmax=posorder (head.right,num);
int maxfromright=num[0]; int curnodemax=maxfromleft+maxfromright+1;
The maximum length of the left and right subtree is added 1 Num[0]=math.max (maxfromleft,maxfromright) +1;
Return Math.max (Math.max (Lmax,rmax), Curnodemax); public static void Main (string[]args) {/** constructed two-forked tree 1 2 3 4 5 6 7
8 */Node Head=new node (1);
Head.left=new Node (2);
Head.right=new Node (3);
Head.left.left=new Node (4);
Head.left.right=new Node (5);
Head.right.left=new Node (6);
Head.right.right=new Node (7);
Head.right.right.left=new Node (8);
The maximum distance System.out.println (getmaxdistance head) between nodes of two fork tree is obtained. }
}