static boolean prefixMatches(Tree target, Tree pattern) { if (pattern.isEmpty()) return true; if (target.isEmpty() || target.value() != pattern.value()) return false; return prefixMatches(target.left(), pattern.left()) && prefixMatches(target.right(), pattern.right()); }
/** Unit tests */ public static void main(String[] args) { final Tree targetTree = tree( 1, tree( 2, tree(3, tree(4), tree(3, tree(4), tree(5))), tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree()))), tree(12)); System.out.println(" Test Pattern"); checkPattern(targetTree, tree(), Optional.of(targetTree)); checkPattern(targetTree, tree(9), Optional.of(tree(9))); checkPattern(targetTree, tree(12), Optional.of(tree(12))); checkPattern(targetTree, tree(13), Optional.empty()); checkPattern(targetTree, tree(1), Optional.of(targetTree)); checkPattern(targetTree, tree(2, tree(3), tree(5)), Optional.of(targetTree.left())); checkPattern( targetTree, tree(3, tree(4), tree(5)), Optional.of(targetTree.left().left().right())); checkPattern( targetTree, tree(6, tree(), tree(8)), Optional.of(targetTree.left().right().left())); checkPattern(targetTree, tree(6, tree(), tree(7)), Optional.empty()); checkPattern( targetTree, tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree())), Optional.of(targetTree.left().right())); }
/** * Search the tree for the first instance of `pattern`, giving preference to the left child. * * <p>`pattern` is a tree, representing a pattern of nodes. `NilNode`s should be considered * wildcards. * * <p>Example patterns ---------------- `Tree()` Matches any tree. * * <p>`Tree(3)` Matches any tree where the root node has a value of `3`. * * <p>`Tree(3, Tree(2), Tree())` Matches any tree where the root node has a value of `3`, and a * left sub-tree with a root value of `2`, and any (or no) right sub-tree. */ static Optional<Tree> find(Tree target, Tree pattern) { if (pattern.isEmpty()) return Optional.of(target); if (target.isEmpty()) return Optional.empty(); if (prefixMatches(target, pattern)) return Optional.of(target); Optional<Tree> leftMatch = find(target.left(), pattern); if (leftMatch.isPresent()) return leftMatch; return find(target.right(), pattern); }