6/21/2020

[LeetCode] 101. Symmetric Tree

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

Compare the given tree and its mirrored tree to check if they are the same.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        
        def compare(lt, rt):
            if not lt or not rt:
                return not lt and not rt
            
            return lt.val == rt.val and \
                   compare(lt.left, rt.right) and \
                   compare(lt.right, rt.left)
        
        return compare(root, root)

Iterative solution:


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        
        stack = [(root, root)]
        
        while stack:
            
            n1, n2 = stack.pop()
            
            if not n1 and not n2:
                continue
                
            if not n1 or not n2 or n1.val != n2.val:
                return False
            
            stack.append((n1.right, n2.left))
            stack.append((n1.left, n2.right))
        
        return True

Edited on 04/22/2021. Add iterative solution.

No comments:

Post a Comment