Java program to find the nodes which are at the maximum distance in a Binary TreeIn this program, we need to find out the nodes which are at the maximum distance in the binary tree. According to our approach, all the distances between all the nodes of the tree will be kept in the variable distance. The distance with the maximum value will be kept by using the variable MaxDistance. Initially, MaxDistance is initialized with the value of distance. If any value is found greater than MaxDistance, overwrite the value of MaxDistance. Repeat this process until we find the maximum possible distance between two nodes of the tree. The algorithm of the process is given below. Algorithm
a. calculateSize() will count the number of nodes present in the tree. b. convertBTtoArray() will convert the binary tree to its array representation by traversing the tree and adding elements to treeArray. c. getDistance() will calculate the distance of a given node from the root. d. LowestCommonAncestor() will find out the lowest common ancestor for the nodes n1 and n2.
a. FindDistance() will calculate the distance between two nodes.
Program:Output: Nodes which are at maximum distance: ( 4, 9 ) ( 5, 9 ) Next TopicJava Programs |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India