Problem statement

https://leetcode.com/problems/symmetric-tree/

Solution

We need to make sure that left subtree is reflected version of right subtree and to do it in recursion way. We can do it, using new function dfs and then apply this function to the root.

Complexity

Time complexity is O(n), space complexity is O(h).

Code

class Solution:
    def isSymmetric(self, root):
        def dfs(n1, n2):
            if not n1 and not n2: return True
            if not n1  or not n2: return False
            
            return n1.val == n2.val and dfs(n1.left, n2.right) and dfs(n1.right, n2.left)
        
        return dfs(root.left, root.right)