菜鸡刷Leetcode之101. Symmetric Tree Easy

Leetcode 101. Symmetric Tree Easy

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

分析:

判断一棵树是否是镜像二叉树。首先,我对树的题目是心存畏惧的,因为这种题目往往涉及递归、循环,而且无法立刻给出思路。但是,现在想想,怕啥,因为关于树的题目套路比较多,通过见多识广,早晚有一天会“见怪不怪”。
首先,我们要明白什么是镜像二叉树——以中央作为对折点,左右两边可以重合,就像镜子一样。镜像二叉树有什么特点呢——根结点的左子树和右子树对称,即左子树的左节点对应着右子树的右节点,二者要相等,以此类推。
在写程序的时候就不难想出以下方法:

/**
 * 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 isSymmetric(TreeNode* root) {
        if (root == nullptr)
            return true;
        return isSymmetricCore(root->left, root->right);
    }
    bool isSymmetricCore(TreeNode* leftRoot, TreeNode* rightRoot) {
        if (leftRoot == nullptr && rightRoot == nullptr)
             return true;
        else if (leftRoot == nullptr || rightRoot == nullptr)
             return false;
        if (leftRoot->val == rightRoot->val)
             return isSymmetricCore(leftRoot->left, rightRoot->right) && isSymmetricCore(leftRoot->right, rightRoot->left);
        return false;            
    }
};

猜你喜欢

转载自www.cnblogs.com/Flash-ylf/p/11095626.html