Skip to content

Latest commit

 

History

History
65 lines (52 loc) · 1.65 KB

File metadata and controls

65 lines (52 loc) · 1.65 KB

101. Symmetric Tree

Solution 1

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
        else:
            return self.isMirror(root.left,root.right)
        
    def isMirror(self,left,right):
        if not (left or right):
            return True
        if (not left) or (not right):
            return False
        
        if left.val==right.val:
            inpair=self.isMirror(left.right,right.left)
            outpair=self.isMirror(left.left,right.right)
            return inpair and outpair
        else:
            return False

{% hint style="info" %} Recursive Method {% endhint %}

Solution 2

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
            if root is None:
                  return True

            stack = [[root.left, root.right]]

            while stack:
                pair = stack.pop()
                left = pair[0]
                right = pair[1]

                if not (left or right):
                    continue
                if (not left) or (not right):
                    return False
                if left.val == right.val:
                    stack.append([left.left, right.right])

                    stack.append([left.right, right.left])
                else:
                    return False
            return True

{% hint style="info" %} Iterative method. {% endhint %}