Last active
December 20, 2015 09:19
-
-
Save enebo/6106691 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static Node find(Node oldRoot, Node oldObject, Node newRoot) { | |
// Walk down the tree to locate oldObject, and in the process, pick the same child for newRoot | |
List<?extends Node> oldChildren = oldRoot.childNodes(); | |
List<?extends Node> newChildren = newRoot.childNodes(); | |
Iterator<?extends Node> itOld = oldChildren.iterator(); | |
Iterator<?extends Node> itNew = newChildren.iterator(); | |
while (itOld.hasNext()) { | |
if (!itNew.hasNext()) { | |
return null; // No match - the trees have changed structure | |
} | |
Node o = itOld.next(); | |
Node n = itNew.next(); | |
if (o == oldObject) { | |
// Found it! | |
return n; | |
} | |
// Recurse | |
Node match = find(o, oldObject, n); | |
if (match != null) { | |
return match; | |
} | |
} | |
if (itNew.hasNext()) { | |
return null; // No match - the trees have changed structure | |
} | |
return null; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static Node find(Node oldRoot, Node oldObject, Node newRoot) { | |
// Walk down the tree to locate oldObject, and in the process, pick the same child for newRoot | |
Iterator<Node> itNew = newRoot.childNodes().iterator(); | |
for (Node o: oldRoot.childNodes()) { | |
if (!itNew.hasNext()) return null; // different number of nodes between trees. mismatch | |
if (o == oldObject) return itNew.next(); // found location in old tree return new equiv. | |
Node match = find(o, oldObject, itNew.next()); // depth-first search | |
if (match != null) return match; | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment