文章目录
0. 题目相关
【题目解读】
给定两颗二叉树,对这两颗二叉树进行比较,判断这两棵二叉树是否相同
【原题描述】原题链接
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
【难度】Easy
1. Solution
二叉树的相关操作基本上都可以通过 先(根)序、中(根)序、后(根)序、层序遍历进行操作。这些遍历操作是最基本的算法,由于长时间没使用,有一些忘记,后面得再补一补这些基本的算法了。
此题使用层序便利进行比较操作,以下是详细代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <queue>
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
queue<TreeNode*> Q1,Q2;
TreeNode *pCurr,*qCurr;
int flag = true;
if(p != NULL && q != NULL)
{
Q1.push(p);
Q2.push(q);
while(!Q1.empty() && !Q2.empty())
{
pCurr = Q1.front();
qCurr = Q2.front();
Q1.pop();
Q2.pop();
if(pCurr->val != qCurr->val)
{
flag = false;
printf("1.break");
break;
}
if(pCurr->left != NULL && qCurr->left != NULL)
{
Q1.push(pCurr->left);
Q2.push(qCurr->left);
}else if(pCurr->left == NULL && qCurr->left == NULL){
printf("%d, %d\n", pCurr->val, qCurr->val);
printf("left is null");
}else{
printf("2.break");
flag = false;
break;
}
if(pCurr->right != NULL && qCurr->right != NULL)
{
Q1.push(pCurr->right);
Q2.push(qCurr->right);
}else if(pCurr->right == NULL && qCurr->right == NULL){
printf("%d, %d\n", pCurr->val, qCurr->val);
printf("right is null");
}else{
printf("3.break");
flag = false;
break;
}
}
}else if(p == NULL && q == NULL)
{
printf("two NULL");
}else
{
flag = false;
}
return flag;
}
};
上述代码提交结果:
由于使用了STL中的queue,借助queue进行层序遍历,所以内存消耗比较大,如果自己实现一个queue,内存会小一些,但还不是最优的。最有代码等待后续再来完善。