Skip to content

[剑指 Offer] 28. 对称的二叉树 #44

@frdmu

Description

@frdmu

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   /
  2   2
 / \ /
3  4 4  3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   /
  2   2
   \  
   3    3

 

示例 1:

输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:

输入:root = [1,2,2,null,3,null,3]
输出:false

 

限制:

  • 0 <= 节点个数 <= 1000

解法一:
按照提示,先求镜像,再比较原来的树和镜像的树是否一样。代码如下,菜鸡写的代码就是啰嗦。。:

/**
 * 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:
    void copy(TreeNode* root, TreeNode*& origin) {
        if (!root) return;

        origin = new TreeNode(root->val);
        
        copy(root->left, origin->left);
        copy(root->right, origin->right);
    }
    TreeNode* mirror(TreeNode* root) {
        if (!root) return root;

        swap(root->left, root->right);

        mirror(root->left);
        mirror(root->right);

        return root;
    }
    bool check(TreeNode* origin, TreeNode* now) {
        if (now && !origin) return false;
        if (!now && origin) return false;
        if (!now && !origin) return true;

        if (now->val == origin->val) {
            return check(origin->left, now->left) && check(origin->right, now->right);    
        }
        
        return false;
    }
    bool isSymmetric(TreeNode* root) {
        if (!root) return true;
        TreeNode* origin;
        copy(root, origin);
        TreeNode* now = mirror(root);
        
        return check(origin, now);
    }
};

解法二:
直接比较树的左右子树是否对称,代码简洁不少。如下:

/**
 * 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:
    bool check(TreeNode* left, TreeNode* right) {
        if (right && !left) return false;
        if (!right && left) return false;
        if (!right && !left) return true;

        if (left->val == right->val) {
            return check(left->left, right->right) && check(left->right, right->left);    
        }   
        return false;    
    }
    bool isSymmetric(TreeNode* root) {
        if (!root) return true;
        
        return check(root->left, root->right);
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions