其他分享
首页 > 其他分享> > LeetCode 101 对称二叉树

LeetCode 101 对称二叉树

作者:互联网

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool dfs(TreeNode* left, TreeNode* right) {
        if (left == nullptr && right != nullptr) return false;
        else if (left != nullptr && right == nullptr) return false;
        else if (left == nullptr && right == nullptr) return true;
        else if (left->val != right->val) return false;
       
        //当外侧或内侧值相等时才进行下一层比较
        bool outside = dfs(left->left, right->right);
        bool inside = dfs(left->right, right->left);

        return outside && inside;
    }
    bool isSymmetric(TreeNode* root) {
        if (root == nullptr) return true;

        return dfs(root->left, root->right);
    }
};

标签:right,TreeNode,val,nullptr,二叉树,return,101,LeetCode,left
来源: https://www.cnblogs.com/hjy94wo/p/16664052.html