Taking a node in rootA and finding a clone node in other tree I was asked this as an interview question. I was also asked to assume that there is a function which can compare and say two nodes are identical. I would like to implement that function as well. I'm not sure what's a sure shot way of saying that in pure JavaScript.


    O         O
   / \       / \
  O   O     O   O
     /|\       /|\
    O O O     O O O

  
  Assume two DOM trees with roots: rootA and rootB, the rootB tree
  being a clone of the rootA tree.  Write a function which takes a node
  in rootA and finds a clone node in the other tree.


I believe there is a better solution than recursion.

jsFiddle

function walkTheDom(root, cb) {
    if (!root) {
        return;
    }
    var r = root;   
    if (cb (r)) {
        foundNode = r;
        return;
    }    
    r = r.firstChild;

    while (r) {
        walkTheDom(r, cb);
        r = r.nextSibling;
    }    

}    

var compare = function (el) {
    //return true if nodes are equal
    //false if they're not
}

function findNode(node, rootB) {
    var foundNode = '';
    walkTheDom(rootB, compare);
    if (foundNode) {
        return foundNode
    }     
}
It looks like the solution solves the wrong problem: the rootA is completely ignored, as well as the fact that the trees are actually DOM. In a DOM structure it is safe to assume that the node has an access to its parent and siblings. So, given a node in rootA tree, you may trace its path to the root, and then descend the same path down from rootB. Since they are clones, such descend will get you to the node in question. I don't see the need (other than unit test purposes) to compare nodes.