menu
announcement

Spectrum is now read-only. Learn more about the decision in our official announcement.

Back To Back SWE

We help software engineers find the job of their dreams with exceptional explanations & teaching resources

Channels
Team

Test If A Binary Tree Is Symmetric - Java and Swift solutions

September 27, 2020 at 10:36pm

Test If A Binary Tree Is Symmetric - Java and Swift solutions

September 27, 2020 at 10:36pm
More tests/trees are probably needed on this problem. It allows a solution that does not require a check for the node's value, just the node's structure.
This solution was allowed to pass on Java and Swift.
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return checkSymmetry(root.left, root.right);
}
private boolean checkSymmetry(TreeNode leftSubtreeRoot, TreeNode rightSubtreeRoot) {
if (leftSubtreeRoot == null && rightSubtreeRoot == null) {
return true;
}
if (leftSubtreeRoot != null && rightSubtreeRoot != null) {
return checkSymmetry(leftSubtreeRoot.right, rightSubtreeRoot.left) &&
checkSymmetry(leftSubtreeRoot.left, rightSubtreeRoot.right);
}
return false;
}
}
No messages yet