1 问题
判断二叉树是不是对称(递归和非递归实现)
如下二叉树,就是对称的二叉树
2
3 3
1 4 4 1
如下二叉树,就是非对称的二叉树
2
3 3
1 4 4 2
2 代码实现
#include <iostream>
#include <queue>
using namespace std;
#define true 1
#define false 0
typedef struct Node
{
int value;
struct Node* left;
struct Node* right;
} Node;
int isSymmetricTree(Node *head);
int isSymmetric(Node *left, Node *right);
int isSymmetricTree1(Node *head);
/*
*判断是否是对称二叉树(递归实现)
*/
int isSymmetricTree(Node *head)
{
if (head == NULL)
{
return true;
}
return isSymmetric(head, head);
}
int isSymmetric(Node *left, Node *right)
{
if (left == NULL && right == NULL)
{
return true;
}
if (left == NULL || right == NULL)
{
return false;
}
if (left->value != right->value)
{
return false;
}
return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left);
}
/*
*判断是否是对称二叉树(非递归实现)
*/
int isSymmetricTree1(Node *head)
{
if (head == NULL)
{
return true;
}
std::queue<Node *> queue1;
std::queue<Node *> queue2;
queue1.push(head->left);
queue2.push(head->right);
while(!queue1.empty() || !queue2.empty())
{
Node *left = queue1.front();
Node *right = queue2.front();
if ((left != NULL) && (right == NULL))
{
return false;
}
if ((left == NULL) && (right != NULL))
{
return false;
}
//因为上面情况只包含left为NULL和right不为NULL以及left不为NULL和right为NULL,
//还包含2种情况,left和right都为NULL,以及left和right都不为NULL,所以我们left->value和right->判断相等的时候
06-16
904
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)