Leetcode 100: Same Tree

grid47
grid47
Exploring patterns and algorithms
Oct 28, 2024 5 min read

Two trees glowing in harmony, showing perfect symmetry and balance.
Solution to LeetCode 100: Same Tree Problem

You are given two binary trees. Your task is to check if these two trees are the same. Two binary trees are considered the same if they are structurally identical and the nodes have the same value at each corresponding position.
Problem
Approach
Steps
Complexity
Input: The input consists of the roots of two binary trees, 'p' and 'q'. Each tree is represented by its root node, and each node contains a value as well as pointers to its left and right children.
Example: p = [3, 5, 8, 2, 6], q = [3, 5, 8, 2, 6]
Constraints:
• 0 <= number of nodes <= 100
• -104 <= Node.val <= 104
Output: The function should return 'true' if the two trees are identical, and 'false' otherwise.
Example: Output: true
Constraints:
• The output should be a boolean value.
Goal: The goal is to recursively check if the structure and values of corresponding nodes in the two trees are the same.
Steps:
• If both trees are empty (i.e., both root nodes are null), return true.
• If one tree is empty and the other is not, return false.
• If both trees are non-empty, check if the value of the current node in both trees is the same.
• Recursively check the left and right subtrees.
Goal: Ensure the function works efficiently for the maximum input size.
Steps:
• The number of nodes in both trees can range from 0 to 100.
Assumptions:
• Both trees are binary trees.
Input: p = [1, 2, 3], q = [1, 2, 3]
Explanation: Both trees are structurally identical and have the same values, so the output is true.

Input: p = [1, 2], q = [1, null, 2]
Explanation: The structures of the trees differ because one tree has a null value where the other tree has a node, so the output is false.

Input: p = [1, 2, 3], q = [1, 1, 2]
Explanation: The trees are not identical because the node values are different at the same positions, so the output is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus