본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 101] Symmetric Tree

by m2162003 2020. 10. 22.

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

 

/**
 * 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 helper(TreeNode* t1, TreeNode* t2){
        if(t1 == nullptr && t2==nullptr){
            return true;
        }
        
        if(t1 == nullptr || t2 == nullptr){
            return false;
        }
        
        return (t1->val == t2->val)
            && helper(t1->right, t2->left)
            && helper(t1->left, t2->right);
    }
    
    bool isSymmetric(TreeNode* root) {
        return helper(root, root);
    }
};

댓글