leetcode 100
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
方法一:利用两个队列分别记录遍历两颗树的节点
//使用两个队列
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
//特殊情况:
//p和q均为空时直接返回true
//p和q中只有一个为空,则返回false
if(p==NULL&&q==NULL)
return true;
if(p==NULL&&q!=NULL||p!=NULL&&q==NULL)
return false;
//利用队列来进行比较
queue<TreeNode *> Queue_p;
queue<TreeNode *> Queue_q;
Queue_p.push(p);
Queue_q.push(q);
while(!Queue_p.empty()&&!Queue_q.empty())//当两个队列均不为空时继续判断
{
TreeNode *node_p=Queue_p.front();//取队列头首个结点
TreeNode *node_q=Queue_q.front();
if(node_p==NULL&&node_q==NULL||node_p!=NULL&&node_q!=NULL&&node_p->val==node_q->val)//当前结点相同时
{
Queue_p.pop();//比较完的节点出队列
Queue_q.pop();
//处理左孩子节点
if(node_p->left&&node_q->left)//左孩子节点均不为空,入队列
{
Queue_p.push(node_p->left);
Queue_q.push(node_q->left);
}
else if(!node_p->left&&!node_q->left) {}//左孩子节点均为空,不操作
else//否则左孩子节点不一样直接返回false
return false;
//处理右孩子节点
if(node_p->right&&node_q->right)//右孩子节点均不为空,入队列
{
Queue_p.push(node_p->right);
Queue_q.push(node_q->right);
}
else if(!node_p->right&&!node_q->right) {}//右孩子节点均为空,不操作
else//否则右孩子节点不一样直接返回false
return false;
}
else
return false;
}
if(Queue_p.empty()&&Queue_q.empty())//当两个队列都为空时,之前的比较全相等故返回true
return true;
else
return false;
}
};
方法二:利用递归
//递归
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(!p&&!q)
return true;
if(p&&!q||!p&&q)
return false;
if(p->val!=q->val)
return false;
else
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
};