# How do you find if two given binary trees are the same or identical?

By | July 16, 2020

In this post, We will learn about How do you find if two given binary trees are the same or identical?

Here We have to write a method in Java, which is going to accept two binary trees and return true if they are the same, otherwise, return false.
Algorithm:

• If both trees are NULL then we return true
• if both trees are NOT NULL then we recursively check left and right subtree structures.

Time Complexity : O(n) , Space Complexity : O(n) for recusive Stack

Below is the Complete Source code: BinaryTree.java

ClientTest.java

The output of This Program:

Binary Tree PreOrder Processing output of both Trees….
1 2 4 5 3 6 7
1 2 4 5 3 6 7
———————————–
Both Trees are Structurally identical

You May Also Like:

That’s all about How do you find if two given binary trees are the same or identical?
If you have any feedback or suggestion please feel free to drop in below comment box.
{"ft_lang_label":"__label__en","ft_lang_prob":0.5624725,"math_prob":0.758653,"size":5888,"snap":"2021-43-2021-49","text_gpt3_token_len":1567,"char_repetition_ratio":0.17284161,"word_repetition_ratio":0.4332211,"special_character_ratio":0.2965353,"punctuation_ratio":0.13644859,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9725184,"pos_list":[0,1,2],"im_url_duplicate_count":[null,4,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-28T01:56:27Z\",\"WARC-Record-ID\":\"<urn:uuid:06c3efc7-7fd7-4c22-a22a-eb58715aa8ec>\",\"Content-Length\":\"100663\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:37149c34-0561-4970-ba16-06bf74d4acb9>\",\"WARC-Concurrent-To\":\"<urn:uuid:e0e7ddb2-e94f-48f0-9eab-0c6c1cf6b35d>\",\"WARC-IP-Address\":\"172.67.213.126\",\"WARC-Target-URI\":\"https://kkjavatutorials.com/how-do-you-find-if-two-given-binary-trees-are-the-same-or-identical/\",\"WARC-Payload-Digest\":\"sha1:YJ4JQC2ND55VZJTV7ERFUAUVW3HUU7DC\",\"WARC-Block-Digest\":\"sha1:DACSSWRUEO5RH7NOKOI6IELJHDAAEDFY\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323588246.79_warc_CC-MAIN-20211028003812-20211028033812-00335.warc.gz\"}"}