Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pseudocode to compare two trees

Tags:

This is a problem I've encountered a few times, and haven't been convinced that I've used the most efficient logic.

As an example, presume I have two trees: one is a folder structure, the other is an in-memory 'model' of that folder structure. I wish to compare the two trees, and produce a list of nodes that are present in one tree and not the other - and vice versa.

Is there an accepted algorithm to handle this?

like image 418
ianmayo Avatar asked Oct 11 '13 05:10

ianmayo


People also ask

How can you tell if two trees are the same?

Two trees 'A' and 'B' are identical if: data on their roots is the same or both roots are null. left sub-tree of 'A' is identical to the left sub-tree of 'B' right sub-tree of 'A' is identical to the right sub-tree of 'B'

How do you compare two nodes in a binary tree?

You would do a parallel tree traversal - choose your order (pre-order, post-order, in-order). If at any time the values stored in the current nodes differ, so do the two trees. If one left node is null and the other isn't, the trees are different; ditto for right nodes.


1 Answers

Seems like you just want to do a pre-order traversal, essentially. Where "visiting" a node means checking for children that are in one version but not the other.

More precisely: start at the root. At each node, get a set of items in each of the two versions of the node. The symmetric difference of the two sets contains the items in one but not the other. Print/output those. The intersection contains the items that are common to both. For each item in the intersection (I assume you aren't going to look further into the items that are missing from one tree), call "visit" recursively on that node to check its contents. It's a O(n) operation, with a little recursion overhead.

like image 157
Jeremy West Avatar answered Sep 29 '22 20:09

Jeremy West