剑指offer 学习笔记 对称的二叉树
面试题28:对称的二叉树。请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
遍历算法中的前序遍历是中左右的顺序遍历的,那么与它对称的树的中右左顺序遍历应该和它的前序遍历顺序相同。
但当一棵树的所有节点值都相等时,只要节点的数量相等,它的前序遍历和前序遍历的对称遍历都是一样的,这时只需要在遍历序列中加入空节点的值即:
#include <iostream>
using namespace std;
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
bool isSymmetrical(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2) {
if (pRoot1 == nullptr && pRoot2 == nullptr) {
return true;
}
if (pRoot1 == nullptr || pRoot2 == nullptr) {
return false;
}
if (pRoot1->m_nValue != pRoot2->m_nValue) {
return false;
}
return isSymmetrical(pRoot1->m_pLeft, pRoot2->m_pRight) && isSymmetrical(pRoot1->m_pRight, pRoot2->m_pLeft);
}
bool isSymmetrical(BinaryTreeNode *pRoot) {
return isSymmetrical(pRoot->m_pLeft, pRoot->m_pRight);
}
int main() {
BinaryTreeNode* pRoot = new BinaryTreeNode();
pRoot->m_nValue = 5;
BinaryTreeNode* pNode1 = new BinaryTreeNode();
pNode1->m_nValue = 7;
pNode1->m_pLeft = pNode1->m_pRight = nullptr;
BinaryTreeNode* pNode2 = new BinaryTreeNode();
pNode2->m_nValue = 7;
pNode2->m_pLeft = pNode2->m_pRight = nullptr;
pRoot->m_pLeft = pNode1;
pRoot->m_pRight = pNode2;
if (isSymmetrical(pRoot)) {
cout << "是对称的。" << endl;
} else {
cout << "不是对称的。" << endl;
}
}