使用从根开始的递归搜索。
一旦在children中找不到匹配项,如果匹配对象的级别比上一个匹配项更深,则记住该匹配对象。
伪代码:
class MatchContext {
public int level;
public Node result;
}
public boolean match(Node object, int level, MatchContext ctx) {
if (no match)
return false;
boolean found = false;
for (all children in object) {
if (match(child, level + 1, ctx))
found = true;
}
if (!found && level > ctx.level) {
ctx.level = level;
ctx.result = this;
}
return found;
}
Run Code Online (Sandbox Code Playgroud)
像这样调用它:
MatchContext ctx;
if (match(root, 0, ctx))
myAction(ctx.result);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |