Any Java Tree API that can be used to find the distance between two terms

My requirement

1) I have to build a tree similar to the one below.

2) I then need to calculate the distance between two terms , say, C and D. or D and F. (according to Figures A and B, the categories C, D, E and F of the terms in the corresponding categories are indicated.

Expected results:

Search Terms ---------- Distance

C and D ---------------------- 2

C and F ---------------------- 4

D and E ---------------------- 4


Link for image:

https://t3.gstatic.com/images?q=tbn:N-Lb_jjMYri3aM:http://skrud.net/files/binary_tree_boat_race.png&t=1

alt text

Java API, , .

API, ....

,

+3
1

, , , .

, , , , node, node . ( , Dijkstra algorithm)

, .

A node :

public class Node {
  public String value; //contains "C" or "D" etc
  public List<Node> children = new ArrayList<Node>();
  public Node parent;
  public Node(Node parent){
    this.parent = parent;
  }
  public Node(Node parent, String value){
    this.parent = value;
    this.value = value;
  }
  public boolean equals(Object n){//Nodes are equal if they have the same value
    return value.equals(((Node)n).value);
  }
}

, A B ( ), distanceTo, node, . , .


, : - , . . node parent node () ( ). A node , . A node - . node , parent null ( , node, ). parent!=null.

Node. 3 ( Node - java ):

Node nodeRoot = new Node(null, "root"); //create a node with parent=null
Node nodeA = new Node(nodeRoot, "A");
Node nodeB = new Node(nodeRoot, "B");
nodeRoot.children.add(nodeA); //you could also place this functionality
nodeRoot.children.add(nodeB); // in the constructor of Node

3 ( nodeRoot) : "root", "A" "B".

, node:

for(Node child:nodeRoot.children){
   System.out.println(child.value);
}
/* prints:
A
B
*/

node:

System.out.println(nodeA.parent.value);
/*prints:
root
*/

, , !

(- > ), - . - - , .


" ": . :

, node .

java, Node. , - , node 0, 1 2 .

: a) b) (BFS/DFS).

+3

Source: https://habr.com/ru/post/1758157/


All Articles