leetcode 100. Same Tree
难度:easy
描述:
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.
解法1
思路:递归
/**
* 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(!q && !p) return true;
if(!q && p) return false;
if(q && !p) return false;
if(p->val != q->val) return false;
if((!p->left && q->left )||(p->left && !q->left )||(!p->right && q->right)||(p->right && !q->right))
{
return false;
}
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};
解法2
思路:借用栈来记录每个节点的信息
/**
* 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;
stack<TreeNode *> s1,s2;
if(p) s1.push(p);
if(q) s2.push(q);
while(!s1.empty() && !s2.empty())
{
TreeNode *t1 = s1.top();s1.pop();
TreeNode *t2 = s2.top();s2.pop();
if(t1->val != t2->val)return false;
if(t1->left) s1.push(t1->left);
if(t2->left) s2.push(t2->left);
if(s1.size()!=s2.size())return false;
if(t1->right) s1.push(t1->right);
if(t2->right) s2.push(t2->right);
if(s1.size()!=s2.size())return false;
}
return s1.size() == s2.size();
}
};