LeetCode---Symmetric Tree

题目大意:给出一个二叉树,判断该树是否关于根节点是中心对称的。

算法思想:

如果一个二叉树是中心对称的,则说明其左右子树对称,由二叉树的性质可知通过前序遍历结果和后序遍历结果可以确定一个二叉树的结构。这样对于对称二叉树,通过将先左子树进行正常的先序和后序遍历,对右子树也进行先序和后序遍历,但注意需要改变一下遍历其左右子树的顺序。无论是先序还是后序左右子树的遍历结果应该相同。如果不相同则不是中心对称的二叉树。

代码如下:


/**
 * 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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值