对称的二叉树

题目

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的

思路

在已学习的二叉树遍历中,都是先遍历左子树,最后遍历右子树,我们可以定义一种算法,先遍历父节点,再遍历左子树,最后遍历右子树,称这种算法为对称遍历算法

  • 如果前序遍历与对称遍历得到的序列相同,则二叉树为对称的(可以自行检测)
  • 考虑到某些结点只有左子树或右子树,则遍历时需要把nullptr考虑进去
#include <iostream>
using namespace std;

struct tree
{
    double data;
    struct tree *left,*right;
    tree(int d=0):data(d)
    {
        left=right=nullptr;
    }
};
class Solution
{
    public:
        void create(tree *&root);
        void pre_order(const tree *root);
        bool is_symmetric();
        bool is_symmetric(const tree *r1,const tree *r2); 
        tree *root;    
};
void Solution::create(tree *&root)
{
    double x;
    cin>>x;
    if(x==0)
        root=nullptr;
    else
    {
        root=new tree();
        root->data=x;
        create(root->left);
        create(root->right);
    }
}
void Solution::pre_order(const tree *root)
{
    if(root)
    {
        cout<<root->data<<endl;
        pre_order(root->left);
        pre_order(root->right);
    }
}
bool Solution::is_symmetric()
{
    return is_symmetric(root,root);
}
bool Solution::is_symmetric(const tree *r1,const tree *r2)
{
    if(!r1&&!r2)
        return true;
    if(!r1||!r2)
        return false;
        
    if(r1->data!=r2->data)
        return false;
    return is_symmetric(r1->left,r2->right)&&is_symmetric(r1->right,r2->left);
}
int main()
{
    Solution s;
    s.create(s.root);
    cout<<boolalpha<<s.is_symmetric()<<endl;
    
    return 0;
}

 

转载于:https://www.cnblogs.com/tianzeng/p/10180718.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值