如何为递归算法实现 "Cancel" 按钮?

How to implement "Cancel" button for a recursive algorithm?

我正在尝试为文件夹同步应用程序中的算法实现 "Cancel" 按钮。该算法递归地遍历用户指定的目录结构,将其文件和目录放入 TreeView 中,并根据它们相对于其他文件夹中的等效项是新的、删除的、更改的还是未更改的来标记它们。精简代码供参考:

fillInTreeView(File x, TreeItem root) {
    if (x.isFile()) {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
    } else {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
        fillInTreeView(x, newBranch);
    }
}

令我感到不安的是 "Cancel" 的含义。如果我让它从顶部删除树中的所有内容,函数是否会继续添加新内容,从取消算法尚未到达的文件中调用自身,使整个按钮毫无意义?我想我宁愿先问而不是花几天时间尝试实施它,只需要稍后再问并重新发现美国。

像这样尝试:

private static boolean cancelled = false;

fillInTreeView(File x, TreeItem root) {
   if(cancelled) return;
   if (x.isFile()) {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
    } else {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
        fillInTreeView(x, newBranch);
    }
}

/*Your CLick-Listener*/
public void onClick(){
       cancelled = true;
}

您应该有一个 return 条件,它只会导致函数 return 该条件。通过在递归调用后检查此 return,您可以快速折叠甚至数以千计的递归。