Given two binary trees, 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.
Tree 1: 1 Tree 2: 1
/ \ / \
2 3 2 3
true
because two empty trees are considered the same.false
because an empty tree cannot be structurally identical to a non-empty tree.If all these conditions are met, the trees are the same.
#include <iostream>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
// If both trees are null, they are same
if (!p && !q) return true;
// If one of them is null, they are not same
if (!p || !q) return false;
// If values of current nodes are different, they are not same
if (p->val != q->val) return false;
// Recursively check left and right subtrees
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
Time Complexity: O(n), where n
is the number of nodes in the tree. This is because each node is visited once.
Space Complexity: O(h), where h
is the height of the trees. This is the maximum depth of the recursion stack.
The provided solution correctly determines if two binary trees are the same by using a recursive function. Each step involves checking the node values and recursively checking the left and right subtrees for equality.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?