题目大意:给出一个二叉树,判断该树是否关于根节点是中心对称的。
算法思想:
如果一个二叉树是中心对称的,则说明其左右子树对称,由二叉树的性质可知通过前序遍历结果和后序遍历结果可以确定一个二叉树的结构。这样对于对称二叉树,通过将先左子树进行正常的先序和后序遍历,对右子树也进行先序和后序遍历,但注意需要改变一下遍历其左右子树的顺序。无论是先序还是后序左右子树的遍历结果应该相同。如果不相同则不是中心对称的二叉树。
代码如下:
/**
* 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:
vector<int> lres,rres;
void pretravel(TreeNode* root,vector<int>& res){
if(root!=NULL){
res.push_back(root->val);
pretravel(root->left,res);
pretravel(root->right,res);
}
}
void rpretravel(TreeNode* root,vector<int>&res){
if(root!=NULL){
res.push_back(root->val);
rpretravel(root->right,res);
rpretravel(root->left,res);
}
}
void intravel(TreeNode* root,vector<int>&res){
if(root!=NULL){
intravel(root->left,res);
res.push_back(root->val);
intravel(root->right,res);
}
}
void rintravel(TreeNode* root,vector<int>&res){
if(root!=NULL){
rintravel(root->right,res);
res.push_back(root->val);
rintravel(root->left,res);
}
}
bool isSymmetric(TreeNode* root) {
if(root==NULL||(root->left==NULL&&root->right==NULL)) return true;
pretravel(root->left,lres);
rpretravel(root->right,rres);
if(lres.size()!=rres.size()) return false;
for(int i=0;i<lres.size();++i){
if(lres[i]!=rres[i])
return false;
}
lres.clear();
rres.clear();
intravel(root->left,lres);
rintravel(root->right,rres);
if(lres.size()!=rres.size()) return false;
for(int i=0;i<lres.size();++i){
if(lres[i]!=rres[i])
return false;
}
return true;
}
};