Update and rename is_tree_symmetric.py to bt_is_tree_symmetric.py

This commit is contained in:
marina 2023-08-03 13:17:44 -07:00 committed by GitHub
parent 5159d766d9
commit 7d6d6189e5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -0,0 +1,43 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: bt3gl
def is_symmetric(root: Optional[Node]) -> bool:
stack = [(root, root)]
while stack:
node1, node2 = stack.pop()
if (not node1 and node2) or (not node2 and node1):
return False
elif not node1 and not node2:
continue
elif node1 and node2 and node1.val != node2.val:
return False
stack.append([node1.left, node2.right])
stack.append([node1.right, node2.left])
return True
def is_symmetric_recursive(root: Optional[TreeNode]) -> bool:
def helper(node1, node2):
if (not node1 and node2) or \
(not node2 and node1) or \
(node1 and node2 and node1.val != node2.val):
return False
if (not node1 and not node2):
return True
return helper(node1.left, node2.right) and helper(node2.left, node1.right)
return helper(root.left, root.right)