“
java,import java.util.ArrayList;,import java.util.List;,,class TreeNode {, int id;, String name;, int level;, List children;,, public TreeNode(int id, String name, int level) {, this.id = id;, this.name = name;, this.level = level;, this.children = new ArrayList();, },, public void addChild(TreeNode child) {, children.add(child);, },},,public class TreeTraversal {, public static void main(String[] args) {, TreeNode root = new TreeNode(1, "根节点", 0);, TreeNode node1 = new TreeNode(2, "子节点1", 1);, TreeNode node2 = new TreeNode(3, "子节点2", 1);, root.addChild(node1);, root.addChild(node2);, node1.addChild(new TreeNode(4, "子节点1-1", 2));, node1.addChild(new TreeNode(5, "子节点1-2", 2));, node2.addChild(new TreeNode(6, "子节点2-1", 2));, node2.addChild(new TreeNode(7, "子节点2-2", 2));,, traverseTree(root);, },, public static void traverseTree(TreeNode node) {, if (node == null) {, return;, }, System.out.println("节点ID: " + node.id + ", 节点名称: " + node.name + ", 层级: " + node.level);, for (TreeNode child : node.children) {, traverseTree(child);, }, },},
“在Java中,我们可以使用递归的方式来查询树形结构的层级,以下是一个简单的示例:
1. 定义树形结构
我们需要定义一个树形结构的节点类TreeNode
,包含节点的值和子节点列表:
import java.util.ArrayList; import java.util.List; public class TreeNode { int value; List<TreeNode> children; public TreeNode(int value) { this.value = value; this.children = new ArrayList<>(); } public void addChild(TreeNode child) { children.add(child); } }
2. 实现查询层级的方法
接下来,我们需要实现一个方法getLevel
,用于查询树形结构的层级,该方法接收两个参数:一个是树的根节点,另一个是目标节点的值,方法的返回值是目标节点的层级。
public class TreeUtils { public static int getLevel(TreeNode root, int targetValue) { return getLevelHelper(root, targetValue, 1); } private static int getLevelHelper(TreeNode node, int targetValue, int level) { if (node == null) { return 1; } if (node.value == targetValue) { return level; } for (TreeNode child : node.children) { int result = getLevelHelper(child, targetValue, level + 1); if (result != 1) { return result; } } return 1; } }
3. 测试代码
我们可以编写一些测试代码来验证我们的实现是否正确:
public class Main { public static void main(String[] args) { TreeNode root = new TreeNode(1); TreeNode child1 = new TreeNode(2); TreeNode child2 = new TreeNode(3); TreeNode child3 = new TreeNode(4); TreeNode child4 = new TreeNode(5); root.addChild(child1); root.addChild(child2); child1.addChild(child3); child1.addChild(child4); System.out.println("Level of node 1: " + TreeUtils.getLevel(root, 1)); // 输出 1 System.out.println("Level of node 2: " + TreeUtils.getLevel(root, 2)); // 输出 2 System.out.println("Level of node 3: " + TreeUtils.getLevel(root, 3)); // 输出 2 System.out.println("Level of node 4: " + TreeUtils.getLevel(root, 4)); // 输出 3 System.out.println("Level of node 5: " + TreeUtils.getLevel(root, 5)); // 输出 3 } }
运行上述测试代码,我们可以看到输出结果与预期相符,说明我们的实现是正确的。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/641765.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复