101. Symmetric Tree

Solution

/**
 * 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_r(root->left, root->right);
    }
    
    bool isSymmetric_r(TreeNode* l, TreeNode* r) {
        if (l == nullptr && r == nullptr) {
            return true;
        }
        
        if (l == nullptr || r == nullptr) {
            return false;
        }
        
        bool isL = isSymmetric_r(l->left, r->right);
        bool isR = isSymmetric_r(l->right, r->left);
        
        if (l->val == r->val && isL && isR) {
            return true;
        }
        
        return false;
    }
};

Complexity

  • Time Complexity: O(N), where N is the number of nodes.
  • Space Complexity: O(N), where N is the size of the implicit call stack.

All Solutions

TODO(alex): Do this exercise iteratively.