MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / is_mirror

Function is_mirror

data_structures/binary_tree/symmetric_tree.py:125–153  ·  view source on GitHub ↗

Check if two subtrees are mirror images of each other. Parameters: left: The root node of the left subtree. right: The root node of the right subtree. Returns: bool: True if the two subtrees are mirrors of each other, False otherwise. Example: >>> tree1 = make_sym

(left: Node | None, right: Node | None)

Source from the content-addressed store, hash-verified

123
124
125def is_mirror(left: Node | None, right: Node | None) -> bool:
126 """
127 Check if two subtrees are mirror images of each other.
128
129 Parameters:
130 left: The root node of the left subtree.
131 right: The root node of the right subtree.
132
133 Returns:
134 bool: True if the two subtrees are mirrors of each other, False otherwise.
135
136 Example:
137 >>> tree1 = make_symmetric_tree()
138 >>> is_mirror(tree1.left, tree1.right)
139 True
140 >>> tree2 = make_asymmetric_tree()
141 >>> is_mirror(tree2.left, tree2.right)
142 False
143 """
144 if left is None and right is None:
145 # Both sides are empty, which is symmetric.
146 return True
147 if left is None or right is None:
148 # One side is empty while the other is not, which is not symmetric.
149 return False
150 if left.data == right.data:
151 # The values match, so check the subtrees recursively.
152 return is_mirror(left.left, right.right) and is_mirror(left.right, right.left)
153 return False
154
155
156if __name__ == "__main__":

Callers 1

is_symmetric_treeFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected