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
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 1000].
-100 <= Node.val <= 100
Follow up: Could you solve it both recursively and iteratively?
Solutions
Solution 1: Recursion
We design a function $\textit{dfs}(\textit{root1}, \textit{root2})$ to determine whether two binary trees are symmetric. The answer is $\textit{dfs}(\textit{root.left}, \textit{root.right})$.
The logic of the function $\textit{dfs}(\textit{root1}, \textit{root2})$ is as follows:
If both $\textit{root1}$ and $\textit{root2}$ are null, the two binary trees are symmetric, and we return true;
If only one of $\textit{root1}$ and $\textit{root2}$ is null, or $\textit{root1.val} \neq \textit{root2.val}$, we return false;
Otherwise, we check whether the left subtree of $\textit{root1}$ is symmetric with the right subtree of $\textit{root2}$, and whether the right subtree of $\textit{root1}$ is symmetric with the left subtree of $\textit{root2}$, using recursion.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 910111213141516
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defisSymmetric(self,root:Optional[TreeNode])->bool:defdfs(root1:Optional[TreeNode],root2:Optional[TreeNode])->bool:ifroot1==root2:returnTrueifroot1isNoneorroot2isNoneorroot1.val!=root2.val:returnFalsereturndfs(root1.left,root2.right)anddfs(root1.right,root2.left)returndfs(root.left,root.right)
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcisSymmetric(root*TreeNode)bool{vardfsfunc(root1,root2*TreeNode)booldfs=func(root1,root2*TreeNode)bool{ifroot1==root2{returntrue}ifroot1==nil||root2==nil||root1.Val!=root2.Val{returnfalse}returndfs(root1.Left,root2.Right)&&dfs(root1.Right,root2.Left)}returndfs(root.Left,root.Right)}