2023-03-13 Daily Challenge

Today I have done leetcode's March LeetCoding Challenge with cpp.

March LeetCoding Challenge 13

Description

Symmetric Tree

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

 

Example 1:

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

Example 2:

Input: root = [1,2,2,null,3,null,3]
Output: false

 

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • -100 <= Node.val <= 100

 

Follow up: Could you solve it both recursively and iteratively?

Solution

auto speedup = [](){
  cin.tie(nullptr);
  cout.tie(nullptr);
  ios::sync_with_stdio(false);
  return 0;
}();
class Solution {
  bool helper(TreeNode *left, TreeNode *right) {
    if(!left && !right) return true;
    if(!left || !right) return false;
    if(left->val != right->val) return false;
    return helper(left->left, right->right) && helper(left->right, right->left);
  }
public:
  bool isSymmetric(TreeNode* root) {
    return helper(root, root);
  }
};

// Accepted
// 197/197 cases passed (8 ms)
// Your runtime beats 50.17 % of cpp submissions
// Your memory usage beats 17.95 % of cpp submissions (16.5 MB)