100. Same Tree
- Recursion
/**
* 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);
}
};
-
T:
-
S:
-
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:
- S: