剑指OFFER----面试题28. 对称的二叉树

链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/

代码:

/**
 * 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 dfs(root->left, root->right);

    }

    bool dfs(TreeNode* p, TreeNode* q) {
        if (!p || !q) return !p && !q;
        if (p->val != q->val) return false;
        return dfs(p->left, q->right) && dfs(p->right, q->left);
    }
};

猜你喜欢

转载自www.cnblogs.com/clown9804/p/12365597.html