The basic idea is to traverse the both tree level by level. Once you find,
the nodes are not the same
or
the nodes are not samely structured
means you found a difference here! now you can mark the level or the node, whatever you want.
PSEDOCODE :
function getDiff(Tree root, Tree root1){
Queue queue->push(root);
Queue queue1->push(root1);
level = 1;
while(queue->size() != 0 && queue1->size() != 0){
if(queue->size() != queue1->size()) {
PRINT: "THE TREE AREN'T IN SAME STRUCTURE :/";
return;
}
size = queue->size();
/* traversing both trees level-by-level */
while(size-- > 0){
Tree temp = queue->peek();
Tree temp1 = queue1->peek();
queue->pop();
queue1->pop();
if(!temp->node != temp1->node) {
PROCESS: level;
}
if(temp->left != null && temp1->left != null) {
queue->push(temp->left);
queue1->push(temp1->left);
}
if(temp->right!= null && temp1->right!= null) {
queue->push(temp->right);
queue1->push(temp1->right);
}
}
/* increase level */
level += 1;
}
}
NOTE: CHANGE THE PSEDOCODE INTO YOUR FAVOURITE LANGUAGE :)
What about a simple hash, List all values from root to leaf of the first tree and hash them. then list all values from root to leaf of the second tree and compare to the first one with O(1) time complexity. One can split the second tree (ig based on the first layer) and use multi thread, In python, just put them on a set; and it's all done. or hash both of them and do a .difference()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.