Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
LeetCode-101: Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
The problem can be solved using a recursive approach. The idea is to check if the left subtree of the root is a mirror of the right subtree of the root.
To check if two trees are a mirror of each other:
null
, then both trees should be null
.Here is a java implementation of the above approach:
public boolean isSymmetric(TreeNode root) {
if(null == root){
return true;
}
return check(root.left, root.right);
}
private boolean check(TreeNode left, TreeNode right){
if(null == left || null == right){
return null == left && null == right;
}
return left.val == right.val
&& check(left.left, right.right)
&& check(left.right, right.left);
}
The time complexity for this approach is $O(N)$, where $N$ is the number of nodes in the binary tree. The space complexity is $O(N)$ as well, considering the recursive stack space.
Be notified of new posts. Subscribe to the RSS feed.