2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
solution
Algorithm ideas
In order to determine the level of the list in the tree structure, we can recursively traverse each node and calculate its depth. Specifically, for each node, we can traverse its parent node upwards until the root node, while accumulating the depth value. The final depth value is the level of the node.
Code Sample
The following is a simple Java code example to determine the level of a node in a tree structure:
public class TreeNode {
private int id;
private int parentId;
public TreeNode(int id, int parentId) {
this.id = id;
this.parentId = parentId;
}
public int getId() {
return id;
}
public int getParentId() {
return parentId;
}
}
public class TreeUtils {
public static int getLevel(TreeNode node, List<TreeNode> nodeList) {
int level = 1;
int parentId = node.getParentId();
while (parentId != 0) {
for (TreeNode n : nodeList) {
if (n.getId() == parentId) {
parentId = n.getParentId();
level++;
break;
}
}
}
return level;
}
}
public class Main {
public static void main(String[] args) {
List<TreeNode> nodeList = new ArrayList<>();
nodeList.add(new TreeNode(1, 0));
nodeList.add(new TreeNode(2, 1));
nodeList.add(new TreeNode(3, 1));
nodeList.add(new TreeNode(4, 2));
TreeNode node = nodeList.get(3);
int level = TreeUtils.getLevel(node, nodeList);
System.out.println("Node " + node.getId() + " is at level " + level);
}
}