Same Tree
EASYDescription
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.
Example 1:
Input: p = [1,2,3], q = [1,2,3] Output: true
Example 2:
Input: p = [1,2], q = [1,null,2] Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2] Output: false
Constraints:
- The number of nodes in both trees is in the range
[0, 100]. -104 <= Node.val <= 104
Approaches
Checkout 3 different approaches to solve Same Tree. Click on different approaches to view the approach and algorithm in detail.
Tree Serialization and Comparison
This approach involves converting each tree into a unique string representation (a process called serialization). If the resulting strings for both trees are identical, the trees are considered the same. A pre-order traversal is a good candidate for serialization, ensuring that null children are also represented to capture the tree's structure accurately.
Algorithm
- Define a helper function
serialize(node, stringBuilder)that performs a pre-order traversal. - In the helper function, if the current
nodeisnull, append a special marker (e.g., "#") and a delimiter to the string builder. - If the
nodeis notnull, append its value and a delimiter, then recursively callserializefor the left and right children. - Create two
StringBuilderinstances. - Call the
serializefunction for the root of treepand treeqto generate their string representations. - Compare the two resulting strings. If they are equal, the trees are identical.
The core idea is to transform the 2D tree structure into a 1D string format. We can define a recursive function that performs a pre-order traversal on a tree. When it encounters a node, it appends the node's value to a string. When it encounters a null child, it appends a special marker (like '#') to signify the absence of a node. This is crucial to distinguish between trees like [1,2] and [1,null,2]. After generating the serialized strings for both trees p and q, we simply compare them. If the strings are equal, the trees are structurally and valuably identical.
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
StringBuilder sb1 = new StringBuilder();
serialize(p, sb1);
String s1 = sb1.toString();
StringBuilder sb2 = new StringBuilder();
serialize(q, sb2);
String s2 = sb2.toString();
return s1.equals(s2);
}
private void serialize(TreeNode node, StringBuilder sb) {
if (node == null) {
sb.append("#,");
return;
}
sb.append(node.val).append(",");
serialize(node.left, sb);
serialize(node.right, sb);
}
}
Complexity Analysis
Pros and Cons
- It's a conceptually straightforward approach if you are familiar with tree serialization.
- It leverages a standard technique that can be reused for other problems like serializing/deserializing a tree.
- This approach is inefficient because it cannot short-circuit. It traverses both entire trees even if a difference is found at the root.
- It uses significant extra space to build the full string representations of both trees.
- The overhead of string building and comparison can be substantial compared to direct node-by-node comparison.
Code Solutions
Checking out 4 solutions in different languages for Same Tree. Click on different languages to view the code.
Video Solution
Watch the video walkthrough for Same Tree
Similar Questions
5 related questions you might find useful
Algorithms:
Data Structures:
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.