java怎么递归查询父子节点

28次阅读
没有评论

共计 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 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-04-07发表,共计947字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)