• 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
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
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
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

    • Bose Ultra Open Earbuds are once again selling at their lowest price by Fiza Ali Amazon is once again offering the Bose Ultra Open Earbuds at their lowest price ever with a limited-time 33 percent discount on their original MSRP, ahead of Father's Day. So, you may want to check it out if you are looking for a gift or if you have been wanting to upgrade your device. The earbuds feature an open-ear design and Bose's OpenAudio technology that should deliver high-quality sound while helping keep audio private. The earbuds also support Bose Immersive Audio, which creates a spatialised listening experience designed to place sound around the listener for a more engaging experience. In terms of wireless connectivity, the earbuds features Bluetooth, Bluetooth Low Energy (BLE), A2DP audio streaming, HFP, AAC, and SBC support. Furthermore, they are compatible with Bose SimpleSync technology, allowing pairing with compatible Bose smart soundbars and speakers. They are also compatible with the Bose App for setup, customisation, and software updates. Moreover, they offer an IPX4 water-resistance rating that should provide protection against sweat and light splashes. When it comes to the battery performance, the Bose Ultra Open Earbuds should provide up to seven hours of battery life on a single charge while a full recharge should take approximately one hour. Specifications Detail Fit type Open-ear Noise cancelling No Microphone Built-in Wireless Bluetooth (A2DP, HFP, AAC, SBC, BLE) Multipoint Yes; 2 devices simultaneously Charging interface USB-C Earbud size 0.73"x0.67" x 1.07" (0.014lb) Case size 1.65"x2.56" x 1.04" (0.097 lb) Materials PC-ABS plastic, metal, silicone, gold plating App support Bose app; adjustable EQ, SimpleSync Audio tech OpenAudio, immersive/spatialized sound Bose Ultra Open Earbuds: $199 (Amazon US) - 33% off Good to know This Amazon deal is U.S. specific, and not available in other regions unless specified. We only use first-party seller links (at the time of article publishing); ensure that you purchase from a first-party seller link only. Check out Today's Deals on Amazon | or our recent tech deals. Become a Prime member (for Students or SNAP) via Neowin Get Prime Access - Prime for half price (for qualifying Medicaid, EBT, SNAP) Subscribe to Prime Video, Audible Plus, Music Unlimited or Kindle Unlimited via Neowin As an Amazon Associate, we earn from qualifying purchases.
    • After enabling it in about:config, customize, density, compact; the toolbar/address bar gets smaller vertically. I enabled Nova, I notice the tab bar/title bar is a bit larger vertically now? Everything always becomes a waste of space.
    • Microsoft's Copilot Cowork now generally available with usage-based billing by Pradeep Viswanathan Back in March, Microsoft first revealed Copilot Cowork, a new agentic AI experience in Microsoft 365 Copilot through which users can assign tasks to AI to complete in the background. After testing the service with a limited set of customers in Research Preview for a few weeks, Microsoft announced the general availability of Copilot Cowork to customers in the Frontier program on March 30. Today, Microsoft announced the general availability of Copilot Cowork worldwide for Microsoft 365 Copilot customers. The company also highlighted that Cowork became the fastest-growing feature in the history of its Frontier program. Unlike regular Copilot Chat, Copilot Cowork can run complex, long-running, multi-tool tasks from start to finish in the cloud by using organizational context through Work IQ. When compared to Claude Cowork, Microsoft claims that Copilot Cowork will be 30% to 40% cheaper on average with its Microsoft 365 connector. For now, Copilot Cowork runs on Anthropic models, including Opus 4.8 and Sonnet 4.6. However, Frontier customers can now use GPT-5.5. Microsoft also announced Cowork 1, a secure fine-tuned model coming in the next few weeks, which is designed to handle everyday Copilot tasks at a lower cost. To access Copilot Cowork, a Microsoft 365 Copilot user subscription is required. Usage is billed separately through Copilot Credits, based on model use, context retrieval, tool calls, and runtime. Pay-as-you-go pricing is set at $0.01 per Copilot Credit. To offer IT teams full control over usage costs, Microsoft provides spending limits, usage alerts, user-level controls, reporting, and prepaid usage plans for organizations. Usage-based billing begins today. However, Frontier customers who used Cowork between March 30 and June 16 will not be billed until July 1, 2026. The Microsoft 365 Copilot app now includes a toggle to enter the full Cowork experience. Microsoft is also adding partner plugins, with Enosix, Harvey, LSEG, Miro, monday.com, Moody’s, Morningstar, S&P Global Energy, and TeamsMaestro available now. Adobe, Atlassian, Box, Canva, Databricks, and others are coming soon.
    • With Nova enabled I am not seeing a difference with compactmode.show?
    • HOLY THREAD REVIVAL   But yes, look for browser.nova.enabled and set it to true
  • Recent Achievements

    • One Year In
      Console General earned a badge
      One Year In
    • One Year In
      Twozo Technologies earned a badge
      One Year In
    • One Month Later
      Twozo Technologies earned a badge
      One Month Later
    • Week One Done
      Twozo Technologies earned a badge
      Week One Done
    • Veteran
      branfont went up a rank
      Veteran
  • Popular Contributors

    1. 1
      +primortal
      522
    2. 2
      +Edouard
      196
    3. 3
      PsYcHoKiLLa
      111
    4. 4
      Steven P.
      90
    5. 5
      Nick H.
      71
  • Tell a friend

    Love Neowin? Tell a friend!