LeetCode 101: Symmetric Tree Solution
Master LeetCode problem 101 (Symmetric Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
101. Symmetric Tree
Problem Explanation
Explanation
To check if a binary tree is symmetric, we can recursively compare the left and right subtrees.
- Define a recursive helper function that takes in two nodes as arguments.
- Check if both nodes are
null, returntrue. - Check if only one of the nodes is
nullor their values are not equal, returnfalse. - Recursively call the helper function with the left node of the left subtree and the right node of the right subtree, and also with the right node of the left subtree and the left node of the right subtree.
- Return the logical
ANDof both recursive calls.
The time complexity of this approach is O(n) where n is the number of nodes in the tree, as we need to visit each node once. The space complexity is O(n) due to the recursive calls on the stack.
Solution Code
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isMirror(root.left, root.right);
}
private boolean isMirror(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null || left.val != right.val) {
return false;
}
return isMirror(left.left, right.right) && isMirror(left.right, right.left);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 101 (Symmetric Tree)?
This page provides optimized solutions for LeetCode problem 101 (Symmetric Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 101 (Symmetric Tree)?
The time complexity for LeetCode 101 (Symmetric Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 101 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 101 in Java, C++, or Python.