Skip to main content

100. Same Tree

Recursion

/*
* @lc app=leetcode id=100 lang=cpp
*
* [100] Same Tree
*
* https://leetcode.com/problems/same-tree/description/
*
* algorithms
* Easy (63.69%)
* Likes: 12070
* Dislikes: 262
* Total Accepted: 2.7M
* Total Submissions: 4.2M
* Testcase Example: '[1,2,3]\n[1,2,3]'
*
* 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].
* -10^4 <= Node.val <= 10^4
*
*
*/

// @lc code=start
/**
* 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 (!p && !q) return true;
if (!p || !q) return false;
if (p->val != q->val) {
return false;
}
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
// @lc code=end
  • T: O(N)O(N)
  • S: O(N)O(N)

Iteration

/**
* 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)
{
queue<TreeNode*> q1, q2;
q1.push(p); q2.push(q);
while (!q1.empty()) {
p = q1.front(); q1.pop();
q = q2.front(); q2.pop();

if (!p && !q) continue;

if (!isSame(p, q)) return false;
if (!isSame(p->left, q->left)) return false;
if (!isSame(p->right, q->right)) return false;

if (p->left)
{
q1.push(p->left);
q2.push(q->left);
}

if (p->right)
{
q1.push(p->right);
q2.push(q->right);
}
}
return true;
}
bool isSame(TreeNode* p, TreeNode* q)
{
if (!p && !q) return true;
if (!p || !q) return false;
return p->val == q->val;
}
};
  • T: O(N)O(N)
  • S: O(N)O(N)