剑指offer 52.对称的二叉树

  1. 题目:请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
  2. 思路:
    1. 将一颗树的左右子树swap,这个题目可以先构造出镜像二叉树,然后判断这两颗树是否相等
  3. 启发或者坑:
    1. 通过递归重新构造一棵树
    2. 比较两棵树是否相等,也可以用递归hh,递归大法好呀
  4. 代码:
    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    */
    class Solution {
    public:
        bool isSymmetrical(TreeNode* pRoot)
        {
            //印象中之前做过这个镜像二叉树,将一颗树的左右子树swap,这个题目可以先构造出镜像二叉树,然后判断这颗树是否相等
            Mirror(pRoot);
            //把这个镜像复制出来
            TreeNode* qRoot = copyTree(pRoot);
            Mirror(pRoot);
            return compareTree(pRoot, qRoot);
        }
        
        void Mirror(TreeNode* pRoot) {
            //这个题目太妙了,交换左右节点;我本来想一层一层遍历把val放在对称的位置【过于复杂,实现困难】
            if (!pRoot)
                return;
            swap(pRoot->left, pRoot->right);
            Mirror(pRoot->left);
            Mirror(pRoot->right);
        }
        
        TreeNode *copyTree(TreeNode* pRoot) {
            if (!pRoot)
                return NULL;
            TreeNode* t = new TreeNode(pRoot->val);
            t->left = copyTree(pRoot->left);
            t->right = copyTree(pRoot->right);
            return t;
        }
        
        bool compareTree(TreeNode* root1, TreeNode* root2) {
            if (!root1 && !root2)
                return true;
            if (!root1)
                return false;
            if (!root2)
                return false;
            if (root1->val!=root2->val)
                return false;
            return compareTree(root1->left, root2->left) && compareTree(root1->right, root2->right);
        }
    };
    
发布了131 篇原创文章 · 获赞 5 · 访问量 7375

猜你喜欢

转载自blog.csdn.net/Alexia23/article/details/104093677