共計 947 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中遞歸查詢父子節點可以使用遞歸算法來實現。以下是一個簡單的示例代碼:
public class TreeNode {private String value;
private List<TreeNode> children;
public TreeNode(String value) {this.value = value;
children = new ArrayList<>();}
public void addChild(TreeNode child) {children.add(child);
}
public TreeNode findChild(String value) {for (TreeNode child : children) {if (child.value.equals(value)) {return child;
} else {TreeNode found = child.findChild(value);
if (found != null) {return found;
}
}
}
return null;
}
public static void main(String[] args) {TreeNode root = new TreeNode("A");
TreeNode b = new TreeNode("B");
TreeNode c = new TreeNode("C");
TreeNode d = new TreeNode("D");
TreeNode e = new TreeNode("E");
root.addChild(b);
root.addChild(c);
b.addChild(d);
b.addChild(e);
TreeNode result = root.findChild("E");
if (result != null) {System.out.println(" 找到了節點:" + result.value);
} else {System.out.println(" 未找到指定節點 ");
}
}
}
在上面的代碼中,我們定義了一個 TreeNode
類來表示樹節點,其中包含一個值和一個子節點列表。通過 findChild()
方法來遞歸查詢子節點,如果找到則返回該子節點,如果沒有找到則返回 null
。在main()
方法中創建了一個簡單的樹結構,并通過遞歸查詢找到了指定節點。
丸趣 TV 網 – 提供最優質的資源集合!
正文完