Symmetric Binary Tree

Medium Problems DSA practice problem on Onlearn.

Difficulty: medium.

Topics: Determining Symmetry in a Binary Tree, Binary Tree, Recursion, Depth-First Search, Node, Time Complexity, Space Complexity, pattern matching, recursion, tree properties, tree traversal, Symmetric Trees.

Problem Statement: Given a Binary Tree, determine whether the given tree is symmetric or not. A Binary Tree would be Symmetric when its mirror image is exactly the same as the original tree. If we were to draw a vertical line through the centre of the tree, the nodes on the left and right side would be mirror images of each other. Input: The input is a binary tree represented by a sequence of integers where 1 denotes a null node. The values are given in a level order traversal fashion. Output: Return True if the binary tree is symmetric, False otherwise. Constraints: The number of nodes in the tree will be between 0 and 10^5. Sample Input 1: 1 2 2 3 4 4 3 Sample Output 1: True Explanation 1: If we were to draw a vertical line through the centre of the tree, dividing it into left and right parts, we observe that the nodes on the left and right sides are mirror images of each other. The root node (1) is at the centre. The left subtree has a node (2) on the left, and the right subtree has a corresponding node (2) on the right. Further, the left subtree of (2) has nodes (3) and (4) from left to right, while the right subtree of (2) has nodes (4) and (3) from right to left. This mirroring pattern continues throughout the tree. The left and right subtrees are symmetrically arranged with respect to the central vertical line. Therefore, the given binary tree is symmetric. Sample Input 2: 1 2 2 1 3 1 3 Sample Output 2: False Explanation 2: While the tree has a symmetric structure at the first level with nodes 2 and 2, the subtrees under nodes 2 and 2 are not symmetric. If we were to draw a vertical line through the centre of the tree, dividing it into left and right parts, we observe that the nodes on the left and right sides are not mirror images of each other.