题目:
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.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
方法一:递归法
比较左子树和右子树是否相同
递归终止条件:两棵树的节点都为空,true;
两棵树只有一颗数节点空,false;
两棵树的节点值不同,false
代码如下:
/**
* 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 == NULL && q == NULL)
return true;
if(p == NULL || q == NULL)
return false;
if(p->val != q->val)
return false;
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
};
方法二:BFS,借助队列
代码如下:
/**
* 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<pair<TreeNode*,TreeNode*> > mQue;
mQue.push(pair<TreeNode*,TreeNode*>(p,q));
while(!mQue.empty())
{
p = mQue.front().first;
q = mQue.front().second;
if(!p ^ !q || (p && q && p->val != q->val))
break;
mQue.pop();
if(p && q)
{
mQue.push(make_pair(p->left,q->left));
mQue.push(make_pair(p->right,q->right));
}
}
return mQue.empty();
}
};
方法三:DFS,借助栈
/**
* 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) {
stack<pair<TreeNode*,TreeNode*> > stk;
stk.push(pair<TreeNode*,TreeNode*>(p,q));
while(!stk.empty())
{
p = stk.top().first;
q = stk.top().second;
if(!p ^ !q || (p && q && p->val != q->val))
break;
stk.pop();
if(p && q)
{
stk.push(make_pair(p->right,q->right));
stk.push(make_pair(p->left,q->left));
}
}
return stk.empty();
}
};