Symmetric Tree — LeetCode 101 (Easy)
Link for leetcode https://leetcode.com/problems/symmetric-tree
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Explanation
All we need to find is if th tree is a mirror tree or not with root as its center so for example if we take an array of [1,2,1] and root is 2 then it will be mirror array so same way we need to cecj if tree is mirror or not
The easiest way we can achive is by using recursion function
we will split each and every tree in to the sub strees and check its content
but as we go deep in to the tree i.e., from 3rd level we need to compare the right tree of oneside to the left tree of another side and vise-versa
So if we consider above example
- for inital call we need to pass (root.left, root.right) as the parameters from there we will compare left to right and right to left
- left assume node1 = root.left and node2 = root.right
- now we will compare if node1 and node2 are None if they are None that means we have reached the end of the tree and the tree is mirror so we will return true
- Next if we do another comparision if node1.val != node2.val if this satisfies that means we encoutered the stage where tree is not a mirror so we return False we dont go furhter
- So if nothing satisifes that measn that values of our nodes are equal and we still have tree to compare
- We compare the left to right and right to left
- so we call (node1.left, node2.right) and (node1.right, node2.left) i.e.,
- If we consider above image as example we will are calling some thing like this (3, 3) and (4, 4) this will be (left of left node, right of right node) and (right of right of left node and left of right node)
- This recursion will continue untill it reaches the end of the node which is our first base case node1 == None and node2 == None
- finally we just return the result from this mirror funciton
It will be more clear once you saw the code, Here is the code with comments
Here we reached the end of the code
Hope you liked my explanation and code, Thanks for reading :)