ZhongKuo0228 / study

0 stars 0 forks source link

101. Symmetric Tree #10

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1:

image

Input: root = [1,2,2,3,4,4,3] Output: true

fockspaces commented 1 year ago

用recursion + 倆倆對稱判斷

/**
 * 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 isSymmetric(TreeNode* root) {
        return isSymmetric(root->left, root->right);
    }

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