• 0

Compare Two Binary Search Trees


Question

I have been trying to figure out a way to compare two Binary Search Trees without multi-threading or any other such parallel computing means. The goal is to test the equivalence of two Binary Search Trees.

The definition of equivalence here is that the number of nodes must be same, and values contained in the two trees must be equal.

For example, see the attached image for two equivalent trees. Now, how would you test the equivalence of these programmatically?

One method I know of is to traverse the tree using any of the traversal methods - Inorder, Preorder, Postorder, etc. and then compare the results with the other tree's. One may even use a BFS or DFS algorithm.

Any other more efficient ways you can think of doing this?

PS: I am NOT in school. This is NOT a homework assignment. I graduated 3 years ago and I am brushing up on data structures. So please keep an open mind. Thanks!

post-47097-1258666711.png

Link to comment
https://www.neowin.net/forum/topic/847418-compare-two-binary-search-trees/
Share on other sites

9 answers to this question

Recommended Posts

  • 0

it seems that what you really want to know is if they both contain the same nodes since the tree structure can be slightly different and still be balanced.

if you have or can keep a node count in your object that is updated as you add and remove nodes, you could use this as your first check to see if the trees are not equal. if both trees dont have the same number of nodes then you know they're not the same search trees. but having the same node count doesnt mean they are equal, so you can only use node counts to more quickly determine that they're not equal.

the next step if they do have an equal node count would be to traverse one tree and search for that node in the second tree. this should be fairly efficient since you're using search trees. the tree that's traversed would have each node touched once, and the tree being searched is s tree used for searching! at any time in this process if you cant find a node from tree A in tree B you can short circuit the comparison because you know the trees are not equal.

the worst case for this method is when the trees are equal since every node in tree A will have been searched and found in tree B and none of the short circuits would have occurred.

there may be other ways of doing this but this is the first way that popped into my head and it seems pretty good.

  • 0

Interesting! Yes, that sounds like a great solution!

What would be the time complexity of the algorithm you proposed? Is it O(N log N)? N for the tree traversal and log N for the search.

The algorithm in my original post was O(N) + O(N) + O(N) (correct me if I am wrong). However, looking at it from an execution time perspective, it would be slower than O(N log N).

  • 0
  Jebadiah said:
Interesting! Yes, that sounds like a great solution!

What would be the time complexity of the algorithm you proposed? Is it O(N log N)? N for the tree traversal and log N for the search.

The algorithm in my original post was O(N) + O(N) + O(N) (correct me if I am wrong). However, looking at it from an execution time perspective, it would be slower than O(N log N).

Well if I am not mistaken if your algorithm was O(N) then it should be faster no matter what the constants are.

In first case you always have 3*N execution time. So we can roughly say if N > 8 then it's faster than the 2nd algorithm. (I haven't studied any of them).

  • 0

I just got back to this thread. You're right again! In the worst case const * O(N) is better than O(N log N). I just did the calculations with some values of N and came to that conclusion. (Damn! I am so rusty with algorithm analyses now.)

To everyone: any other creative solutions for the original question that you can think of?

  • 0
  Jebadiah said:
That is the solution I talk about in my first post. :)

The preorder and postorder traversals would not produce the numbers in the same order though. And yeah, that seems to be the fastest solution I can currently think of (since it's pretty ****ing fast).

  • 0

function structeq (t1, t2 : tree) : boolean;
begin 
  if t1 = nil										then structeq := t2 = nil
  else if t2 = nil								 then structeq := false
  else if structeq(t1^.left, t2^.left)   then structeq := structeq(t1^.right, t2^.right)
  else												structeq := false
end

That's not my code. But it checks if two tree's have the same structure. To check the values as well you probably need to use "AND" t1.value = t2.value. Probably better to use it with C though, the short-circuited && will come in handy when you want to check the value only if the pointer is not null. (Pascal would require nested if's which is just biah). It's basically what you said, written in Pascal in a neat way.

You can't go any faster than that as far as I know.

  • 0
  gianpan said:
function structeq (t1, t2 : tree) : boolean;
begin 
  if t1 = nil										then structeq := t2 = nil
  else if t2 = nil								 then structeq := false
  else if structeq(t1^.left, t2^.left)   then structeq := structeq(t1^.right, t2^.right)
  else												structeq := false
end

That's not my code. But it checks if two tree's have the same structure. To check the values as well you probably need to use "AND" t1.value = t2.value. Probably better to use it with C though, the short-circuited && will come in handy when you want to check the value only if the pointer is not null. (Pascal would require nested if's which is just biah). It's basically what you said, written in Pascal in a neat way.

You can't go any faster than that as far as I know.

Cool! That way you can check if the two trees are identical in terms of value and structure together in O(N) time. It looks like a Preorder lockstep traversal. Good one!

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Kindle Scribe Essentials Bundle offers great value for students and professionals by Paul Hill Earlier this week, we featured the Kindle Scribe in a deals post. Amazon’s largest Kindle had fallen to its lowest price; these are still on offer if you’re interested. Now, the company has also decided to discount the Kindle Scribe Essentials Bundle, which includes the Kindle Scribe with Premium Pen, premium leather folio, and a 9W power adapter. The Premium Pen is already included with the Kindle Scribe, but this bundle adds the premium leather folio and 9W power adapter. The 64GB Kindle Scribe variants (available in two colors) cost $404.97, down from $569.97. By using this deal, you’re saving $165 off the list price and it’s $65 less than if you bought the bundle items separately. In the original deal, which is still available, you got the Kindle and the pen, so this bundle adds the 9W power adapter and the premium leather folio. If you are still looking for Father’s Day gifts, this Kindle Scribe Essentials Bundle will not arrive in time, even if you get a Prime member trial. What the Kindle Scribe does The Kindle Scribe features a large 10.2-inch glare-free display with a 300 ppi density. It comes with a Premium Pen that makes it feel like you’re writing on paper as you jot down your notes. To make writing easier, you get Active Canvas for in-book notes and a built-in notebook with templates. You can import and write on PDFs and documents via Send to Kindle, including sending directly from Word if you have a Microsoft 365 subscription. With the inclusion of the natural leather folio, which patinas over time, you are able to wake and sleep your Kindle Scribe by opening and closing the folio. It uses a magnetic attachment to ensure a secure close. Once you have written out your notes, the Kindle Scribe allows you to summarize them using artificial intelligence. You can even customize the length and tone of your notes. You can also refine your notes by converting your handwritten words into a script font. One of the standout features of other Kindle devices is their spectacular battery life, and the Kindle Scribe promises the same. The battery will last you up to 12 weeks for reading and up to 3 weeks for writing. Furthermore, Amazon has used 18% recycled materials including 100% recycled aluminum parts, and it comes in fully recyclable packaging. Finally, and it shouldn’t really need mentioning, the Kindle Scribe has full access to the Kindle Store so you can quickly and easily gain access to all of the latest books. Should you buy it? Anyone who has ever loved using a Kindle product should check out the Scribe as it has many of the same characteristics, but on a bigger scale and with writing capabilities. Students at college, especially those studying something like literature, could benefit. It could also be good for professionals who need to annotate documents. If you saw the deal earlier this week and were worried about scuffing up the device, then this deal may be more tempting thanks to the inclusion of the folio case. Amazon Kindle Scribe Essentials Bundle (16GB): $359.97 (Amazon US) / MSRP $519.97 Amazon Kindle Scribe Essentials Bundle (32GB): $374.97 (Amazon US) / MSRP $539.97 Amazon Kindle Scribe Essentials Bundle (64GB, Tungsten/Black Folio): $404.97 (Amazon US) / MSRP $569.97 Amazon Kindle Scribe Essentials Bundle (64GB, Metallic Jade/Dark Emerald Folio): $404.97 (Amazon US) / MSRP $569.97 This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • sounds like this same jet had electrical failures in a prior flight including the entertainment systems, and call buttons and other things not working
    • That's the publisher's fault and happens with or without GamePass. Microsoft at least offers the Play Anywhere option.
    • Windows Phone actually had some great features, the problem Microsoft had is that developers are not used to having to deal with stores etc. and they couldn't get them onboard. But there were a lot of good features, in fact we see more and more of them popping up on other OS' all the time.
  • Recent Achievements

    • First Post
      NeoToad777 earned a badge
      First Post
    • Week One Done
      JoeV earned a badge
      Week One Done
    • One Month Later
      VAT Services in UAE earned a badge
      One Month Later
    • First Post
      LsDmT earned a badge
      First Post
    • Week One Done
      evershinefacilityservice earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      571
    2. 2
      ATLien_0
      247
    3. 3
      +Edouard
      162
    4. 4
      +FloatingFatMan
      151
    5. 5
      Michael Scrip
      113
  • Tell a friend

    Love Neowin? Tell a friend!