15 Jun 2024C++ / Python / TypeScriptEasy

Symmetric Tree

Collected C++, Python, TypeScript solutions for symmetric tree. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Symmetric Tree. the solution files are available below.

solution files

  • C++ symmetric-tree/synced-solution.cpp
  • Python symmetric-tree/synced-solution.py
  • TypeScript symmetric-tree/synced-solution.ts

Solution files

Pythonsymmetric-tree/synced-solution.py
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def isMirror(t1, t2):
            if not t1 and not t2:
                return True
            if not t1 or not t2:
                return False
            return t1.val == t2.val and isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left)
        return isMirror(root, root)
C++symmetric-tree/synced-solution.cpp
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        return isMirror(root, root);
    }
private:
    bool isMirror(TreeNode* t1, TreeNode* t2) {
        if (!t1 && !t2) return true;
        if (!t1 || !t2) return false;
        return t1->val == t2->val && isMirror(t1->left, t2->right) && isMirror(t1->right, t2->left);
    }
};
TypeScriptsymmetric-tree/synced-solution.ts
function isSymmetric(root: TreeNode | null): boolean {
    function isMirror(t1: TreeNode | null, t2: TreeNode | null): boolean {
        if (!t1 && !t2) return true;
        if (!t1 || !t2) return false;
        return t1.val === t2.val && isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left);
    }
    return isMirror(root, root);
}