题目
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 1:
输入:
1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
输出: true
示例 2:
输入:
1 1
/ \
2 2
[1,2], [1,null,2]
输出: false
示例 3:
输入:
1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/same-tree
解题思路
这一题考察的还是遍历,只需要在遍历过程中判断结点是否匹配(同时为NULL或同时不为NULL),对应结点的值是否相同
代码(C++)
非递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL&&q!=NULL) return false;
if(q==NULL&&p!=NULL) return false;
stack<TreeNode*> st1;
stack<TreeNode*> st2;
while(!st1.empty()||p){
while(p){
if(q){
if(p->val==q->val){
st1.push(p);
st2.push(q);
p=p->left;
q=q->left;
}
else{
return false;//对应结点值不同
}
}
else{
return false;//结点不匹配
}
}
if(q!=NULL){
return false;//结点不匹配
}
p=st1.top();
q=st2.top();
st1.pop();
st2.pop();
p=p->right;
q=q->right;
}
return true;
}
};
递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL&&q==NULL) return true;
if(p==NULL&&q!=NULL) return false;
if(q==NULL&&p!=NULL) return false;
if(q->val!=p->val) return false;
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};