Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether given tree is symmetric tree or not in Python
A symmetric binary tree is one that looks identical to its mirror image. To check if a tree is symmetric, we need to verify that the left subtree is a mirror reflection of the right subtree.
Algorithm
To check if a tree is symmetric, we use a recursive approach comparing the left and right subtrees ?
Compare the root with itself using a helper function
If both nodes are null, return True
If one node is null and the other isn't, return False
If both nodes have the same value, recursively check if left subtree mirrors right subtree
Implementation
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root):
"""Check if binary tree is symmetric"""
return self.isMirror(root, root)
def isMirror(self, node1, node2):
"""Helper function to check if two subtrees are mirrors"""
# Both nodes are None
if not node1 and not node2:
return True
# One node is None, other is not
if not node1 or not node2:
return False
# Check current nodes and recursively check subtrees
return (node1.data == node2.data and
self.isMirror(node1.left, node2.right) and
self.isMirror(node1.right, node2.left))
# Create symmetric tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.left = TreeNode(4)
root.right.right = TreeNode(3)
solution = Solution()
print("Is symmetric:", solution.isSymmetric(root))
Is symmetric: True
Testing Non-Symmetric Tree
# Create non-symmetric tree
root2 = TreeNode(1)
root2.left = TreeNode(2)
root2.right = TreeNode(2)
root2.left.right = TreeNode(3)
root2.right.right = TreeNode(3)
solution = Solution()
print("Is symmetric:", solution.isSymmetric(root2))
Is symmetric: False
How It Works
The algorithm works by comparing corresponding positions in the left and right subtrees. For a tree to be symmetric:
The left child of the left subtree must equal the right child of the right subtree
The right child of the left subtree must equal the left child of the right subtree
This pattern continues recursively for all levels
Time and Space Complexity
Time Complexity: O(n) where n is the number of nodes, as we visit each node once.
Space Complexity: O(h) where h is the height of the tree due to the recursive call stack.
Conclusion
A symmetric tree check requires comparing left and right subtrees recursively. The key insight is that for symmetry, the left subtree must be a mirror image of the right subtree at every level.
