(Java)使用从二叉树输出布尔值的功能(类谓词)接口

我有点麻烦:我构建了一个二叉树类,其中包含一些对于此任务而言并不有趣的函数。每个节点都存储一个左右子节点和一个父节点。每个节点都有一个键值,可以看作是一个标签。我创建了 3 个类:


Tree.java 是一个节点的类。


BinaryTree.java 包含一些与整个树相关的方法,例如最小值/最大值。


Main.java 测试 Tree 的特性并包含 main 方法。


我的问题: 我想用一个方法编写一个功能接口,该方法将节点作为参数并输出一个布尔值。这可用于传入根节点并递归检查树中的每个节点是否大于或小于一个值。但是,我对功能接口完全陌生,我无法真正掌握功能背后的逻辑。这是我到目前为止得到的:


@FunctionalInterface


public interface NodeOperation {

    public abstract boolean forAll(Tree node);

}


NodeOperation overTwenty = (node) -> node.getValue() < 20;

当我尝试使用 lambda 表示法时,当我想打印 overTwenty 时它不会返回布尔值。有人可以帮我实现功能接口并解释我如何访问布尔变量,以便我可以开始考虑如何为每个节点递归地执行此操作。


如果您对二叉树不太了解,建议您在 Wikipedia 上查找。就我而言,我制作了一个 BST(二叉搜索树),这意味着它的结构基于右侧的较大值和左侧的较小值。如果您需要我的代码的某些特定部分,只需提出建议,我将在此处发布:)


哈士奇WWW
浏览 164回答 2
2回答

HUWWW

在java中,接口的方法总是公开的。所以你的界面可以变成@FuctionalInterface&nbsp; &nbsp; public interface NodeOperation {&nbsp; &nbsp; &nbsp; &nbsp; boolean forAll(Tree node);&nbsp; &nbsp; }所以你写了这行代码NodeOperation overTwenty = (node) -> node.getValue() < 20;Wich 会为您创建一个接口实例,用于检查节点的值是否低于 20因此,假设您有一个值为 30 的 Tree 节点实例,如果您调用&nbsp;overTwenty.forAll(node) //will return false这个函数不是递归的。如果要将函数应用于节点的所有子节点,则必须在 Tree 类上编写递归方法&nbsp; &nbsp;public class Tree{&nbsp; &nbsp; &nbsp; &nbsp;...&nbsp;&nbsp; &nbsp; public boolean recursiveNodeOperation(NodeOperation operation) {&nbsp; &nbsp; &nbsp; &nbsp;if(!operation.forAll(this)) return false;&nbsp; &nbsp; &nbsp; &nbsp;for(Tree child : children)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(! child.recursiveNodeOperation(operation))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp;return true ;&nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; }&nbsp;root.recursiveNodeOperation(overTwenty); //will return true if all the nodes of the Tree starting from root are lower than 20此方法将递归应用 Node 操作,因此将检查 Tree 中的所有元素是否与您的函数匹配

MMTTMM

您创建的overTwenty对象是一个函数。如果要在树的节点中使用它,则必须在树的节点上调用它的唯一方法。例如,您可以这样称呼它:boolean&nbsp;result&nbsp;=&nbsp;overTwenty.forAll(root);顺便说一句,您的NodeOperationinterface 与 a 非常等价,Function<Tree, Boolean>只是它返回的是原语boolean而不是 class&nbsp;Boolean。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java