• 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

    • BleachBit 6.0.1 Beta by Razvan Serea When your computer is getting full, BleachBit quickly frees disk space. When your information is only your business, BleachBit guards your privacy. With BleachBit you can free cache, delete cookies, clear Internet history, shred temporary files, delete logs, and discard junk you didn't know was there. Designed for Linux and Windows systems, it wipes clean thousands of applications including Firefox, Microsoft Edge, Google Chrome, Opera, Safari, and more. Beyond simply deleting files, BleachBit includes advanced features such as shredding files to prevent recovery, wiping free disk space to hide traces of files deleted by other applications, and vacuuming Firefox to make it faster. Better than free, BleachBit is open source. BleachBit has many useful features: Delete your private files so completely that "even God can't read them" according to South Carolina Representative Trey Gowdy. Simple operation: read the descriptions, check the boxes you want, click preview, and click delete. Multi-platform: Linux and Windows Free of charge and no money trail Free to share, learn, and modify (open source) No adware, spyware, malware, browser toolbars, or "value-added software" Translated to 64 languages besides American English Shred files to hide their contents and prevent data recovery Shred any file (such as a spreadsheet on your desktop) Overwrite free disk space to hide previously deleted files Portable app for Windows: run without installation Command line interface for scripting and automation CleanerML allows anyone to write a new cleaner using XML Automatically import and update winapp2.ini cleaner files (a separate download) giving Windows users access to 2500+ additional cleaners Frequent software updates with new features Going beyond standard deletion of files, BleachBit has several advanced cleaners: Clear the memory and swap on Linux Delete broken shortcuts on Linux Delete the Firefox URL history without deleting the whole file—with optional shredding Delete Linux localizations: delete languages you don't use. More powerful than localepurge and available on more Linux distributions. Clean APT for Debian, Ubuntu, Kubuntu, Xubuntu, and Linux Mint Find widely-scattered junk such as Thumbs.db and .DS_Store files. Execute yum clean for CentOS, Fedora, and Red Hat to remove cached package data Delete Windows registry keys—often where MRU (most recently used) lists are stored Delete the OpenOffice.org recent documents list without deleting the whole Common.xcu file Overwrite free disk space to hide previously files Vacuum Firefox, Google Chrome, Liferea, Thunderbird, and Yum databases: shrink files without removing data to save space and improve speed Surgically remove private information from .ini and JSON configuration files and SQLite3 databases without deleting the whole file Overwrite data in SQLite3 before deleting it to prevent recovery (optional) BleachBit 6.0.1 Beta release notes: BleachBit 6.0.1 beta is now available for testing. This maintenance-focused release includes bug fixes, updated translations, and a range of safe enhancements. This release fixes a Windows security issue that could allow arbitrary file deletion during privileged cleaning (reported by Zeze with TeamT5). It also adds new cleaners (including a DNS cache cleaner, Claude Code, and Visual Studio Code forks), support for multiple Chrome and Edge profiles, new deep scan options for developer directories like node_modules and venv, and safer, faster file shredding. All Platforms Added cleaners for Claude Code, DNS cache, and many Visual Studio Code forks. Added support for multiple Chrome and Edge profiles. Chrome can now clean downloaded AI models. Deep Scan can optionally remove venv, __pycache__, node_modules, and .angular directories. Deep Scan is faster by skipping directories on the keep list. File shredding is safer, faster, and leaves fewer recoverable traces. Improved handling of cookies, symlinks, Unicode filenames, external processes, and configuration files. Improved Expert Mode warnings and long warning dialogs. Fixed crashes related to cleaner detection, invalid Unicode, and malformed cleaner data. Clipboard is now cleared automatically after shredding files via paste operations. Linux Added AppImage support. Added cleaners for Visual Studio Code, Codeium, Librewolf (.deb), Transmission (Flatpak), and Profanity. Improved Linux trash detection, including Snap-installed applications and mounted drives. Fixed Wayland root CLI issues and several Snap-related problems. Improved package dependencies, AppStream metadata, and desktop file handling. Fixed startup crashes when Python Requests is unavailable. Windows Fixed a security vulnerability that could allow arbitrary file deletion when cleaning with elevated privileges. Added %WindowsSystem% variable support. Improved clipboard clearing using native Windows APIs. Improved installer experience on unsupported Windows versions. Reduced installer size and improved application robustness. Fixed Unicode handling, filename anonymization, Git revision reporting, and splash screen stability. [full release notes] Download: BleachBit 6.0 | Portable | ~20.0 MB (Open Source) View: BleachBit Home page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • DriversCloud 12.1.6 by Razvan Serea With DriversCloud (formerly My-Config.com), you can explore your computer easily, safely and free. The application quickly scans your PC and identifies the hardware and software components. DriversCloud then establishes a list of the different drivers compatible with your OS and hardware. Download the drivers needed for the proper functioning of your computer. To detect your drivers, DriversCloud also displays a detailed summary of your hardware and software configuration, analyzes your BSOD, monitors in real-time your PC voltages and temperatures and lets you share your configuration online. Once the hardware components have been detected, you will be able to obtain with just a few clicks the latest drivers corresponding to the identified hardware. You can record your configuration on the site for free, and can get the corresponding URL to post the configuration to technical forums, e-mail and social networks. You can also download the detection result (the configuration) as a PDF file. To protect the user's privacy and data confidentiality, a 4-level confidentiality system was created that filters the XML marks and gives control to the user. The default level can be modified in the preferences. Using the maximum level will prevent the user from publishing his configuration and generating a corresponding PDF file. In non-connected mode, each XML configuration is stored on the server for one day (for practical reasons). However, you are given the opportunity to manually delete it. Created in 2004, and continually improved, My-Config.com has established itself on the web as a free service to PC users running Windows and Linux operating systems. The service is designed to work with the most common Internet browsers (Edge, Firefox, Chrome, Safari). Download: DriversCloud 64-bit | 20.0 MB (Freeware) Download: DriversCloud 32-bit | 18.9 MB Link: DriversCloud Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Ocenaudio 3.19.3 by Razvan Serea  Ocenaudio is a full featured, fast and easy to use audio and music editor. It is the ideal software for people who need to edit and analyze audio files without complications. Ocenaudio also has powerful features that will please more advanced users. To assist ocenaudio development, a powerful toolset of audio editing, analysis and manipulation called Ocen Framework was created. ocenaudio is also based on Qt framework, a well known library for cross-platform development. Cross-platform support ocenaudio is available for all major operating systems: Microsoft Windows, Mac OS X and Linux. Native applications are generated for each platform from a common source, in order to achieve excelent performance and seamless integration with the operating system. All versions of ocenaudio have a uniform set of features and the same graphical interface, so the skills you learn in one platform can be used in the others. VST plugins support Ocenaudio supports VST (Virtual Studio Technology) plugins, giving its users access to numerous effects. Like the native effects, VST effects can use real-time preview to aide configuration. Real-time preview of effects Applying effects such as EQ, gain and filtering is an important part of audio editing. However, it is very tricky to get the desired result by adjusting the controls configuration alone: you must listen the processed audio. To ease the configuration of audio effects, ocenaudio has a real time preview feature: you hear the processed signal while adjusting the controls. The effect configuration window also includes a miniature view of the selected audio signal. You can navigate on this miniature view in the same way as you do on the main interface, selecting parts that interest you and listening to the effect result in real time. Multiselection for delicate editions To speed up complex audio files editing, ocenaudio includes multi-selection. With this amazing tool, you can simultaneously select different portions of an audio file and listen, edit or even apply an effect to them. For example, if you want to normalize only the excerpts of an interview where the interviewee is talking, just select them and apply the effect. Eficient edition of large files With ocenaudio, there is no limit to the length or the quantity of the audio files you can edit. Using an advanced memory management system, the application keeps your files open without wasting any of your computer's memory. Even in files several hours long, common editing operations such as copy, cut or paste happen almost instantly. Fully featured spectrogram Besides offering an incredible waveform view of your audio files, ocenaudio has a powerful and complete spectrogram view. In this view, you can analyze the spectral content of your audio signal with maximum clarity. Advanced users will be surprised to find that the spectrogram settings are applied in real time. The display is updated immediately when altering features such as the number of frequency bands, window type and size and dynamic range of the display. Ocenaudio 3.19.3 changelog: Fixes issues with MP4 files with more than 8 channels Fixes incorrect VBR detection for some CBR MP3 files Other bug fixes and improvements Download: Ocenaudio 64-bit | Portable | ~40.0 MB (Freeware) Download: Ocenaudio for Linux and Mac OS View: Ocenaudio Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      agatameier earned a badge
      Week One Done
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      513
    2. 2
      +Edouard
      186
    3. 3
      PsYcHoKiLLa
      144
    4. 4
      ATLien_0
      95
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!