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

LeetCode 101 对称二叉树

时间:2022-09-07 09:00:07浏览次数:84  
标签:right TreeNode val nullptr 二叉树 return 101 LeetCode left

/**
 * 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
From: https://www.cnblogs.com/hjy94wo/p/16664052.html

相关文章