【LeetCode】101. 对称二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuqiuai/article/details/83381997

题目链接https://leetcode-cn.com/problems/symmetric-tree/description/

题目描述

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [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

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

解决方法

思路:将二叉树分割为左子树和右子树,再判断两棵树是否对称

/**
 * 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) return true;
        return isDui(root->left,root->right);
    }
private:
    bool isDui(TreeNode* p, TreeNode* q) {
        if (!p && !q) return true; //两棵树都为空返回true
        if ((p && !q) || (!p && q)) return false; //只有一棵树为空返回false
        if (p->val==q->val && isDui(p->left,q->right) && isDui(p->right,q->left)) return true;//节点值相等,且左右子树分别对称,则返回true
        else return false;
    }
};

猜你喜欢

转载自blog.csdn.net/fuqiuai/article/details/83381997