mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-06 16:55:17 -04:00
add some fun tree playing
This commit is contained in:
parent
48720ada4d
commit
bb72bab679
6 changed files with 209 additions and 0 deletions
38
trees_and_graphs/is_tree_symmetric.py
Normal file
38
trees_and_graphs/is_tree_symmetric.py
Normal file
|
@ -0,0 +1,38 @@
|
|||
def is_symmetrical(root: Optional[TreeNode]) -> 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_symmetrical_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)
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue