Checking if Two Binary Trees are Identical

Day - 91 Same Tree The problem -Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Brute Force - Perform level-order traversal on both trees, store all node values and structure in separate lists, then compare the lists. This gives O(n) time but requires O(n) extra space for storing traversal results, which is unnecessary. Approach Used - •) If both p == null AND q == null, return true, both trees are empty, hence identical. •) If p == null OR q == null OR p.val != q.val, return false, one tree is empty while other isn’t or node values differ. •) Return isSameTree(p.left, q.left) && isSameTree(p.right, q.right), recursively compare left subtrees and right subtrees, both must be true for trees to be identical. Complexity - Time - O(min(n, m)), where n and m are number of nodes. Space - O(min(h₁, h₂)), where h₁, h₂ are heights of trees. Note - Two trees are identical if and only if their current nodes match AND their left subtrees are identical AND their right subtrees are identical. By recursively checking these three conditions, we efficiently verify tree equality in a single traversal. The base cases handle structural differences (null vs non-null) while the recursive case handles value and subtree comparisons. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories