1
+ from collections import deque
2
+
3
+ def symmetric_tree (root ):
4
+ """
5
+ Determine if a binary tree is symmetric around its center.
6
+
7
+ Parameters:
8
+ root (Node): The root node of the binary tree.
9
+
10
+ Returns:
11
+ bool: True if the tree is symmetric, False otherwise.
12
+ """
13
+ queue = deque ([root .left , root .right ])
14
+
15
+ while queue :
16
+ curr_left = queue .popleft ()
17
+ curr_right = queue .popleft ()
18
+
19
+ # If both nodes are None, they are symmetric; continue to the next pair
20
+ if not curr_left and not curr_right :
21
+ continue
22
+
23
+ # If only one of the nodes is None, the tree is not symmetric
24
+ if not curr_right or not curr_left :
25
+ return False
26
+
27
+ # If the values of the nodes are not equal, the tree is not symmetric
28
+ if curr_left .val != curr_right .val :
29
+ return False
30
+
31
+ # Append children in mirrored order to maintain symmetry check
32
+ queue .append (curr_left .left )
33
+ queue .append (curr_right .right )
34
+ queue .append (curr_left .right )
35
+ queue .append (curr_right .left )
36
+
37
+ return True
38
+
39
+ # Approach:
40
+ # ---------
41
+ # The function uses an iterative approach with a queue to perform a level-order traversal,
42
+ # comparing nodes in pairs to check for symmetry. The idea is to compare the left and right
43
+ # subtrees of the tree simultaneously, ensuring that they mirror each other.
44
+
45
+ # Steps:
46
+ # 1. Initialize a queue with the left and right children of the root.
47
+ # 2. While the queue is not empty, pop two nodes at a time (curr_left and curr_right).
48
+ # 3. If both nodes are None, continue to the next pair (they are symmetric).
49
+ # 4. If only one of the nodes is None, return False (they are not symmetric).
50
+ # 5. If the values of the nodes are not equal, return False (they are not symmetric).
51
+ # 6. Append the children of curr_left and curr_right to the queue in a mirrored order:
52
+ # - Append curr_left.left and curr_right.right
53
+ # - Append curr_left.right and curr_right.left
54
+ # 7. If all pairs are symmetric, return True.
55
+
56
+ # Time Complexity:
57
+ # ----------------
58
+ # O(n), where n is the number of nodes in the tree. Each node is enqueued and dequeued once.
59
+
60
+ # Space Complexity:
61
+ # -----------------
62
+ # O(n), where n is the number of nodes in the tree. In the worst case, the space used by the queue
63
+ # is proportional to the number of nodes at the widest level of the tree, which can be up to n/2.
0 commit comments