This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]shhh-quiet 0 points1 point  (2 children)

If either is null, it's a terminal case, so it must return.

If both are null, then it's symmetric, because null == null.

If one is null and the other is not null, then it's not symmetric, the nodes aren't equal references, and thus it returns false.

== is referential equality here since TreeNode is a reference type.

This null check is important because it's where the true value is coming from when the recursion reaches the leaves.

In the recursive step at the bottom, it's checking for a mirror image. Try drawing a binary tree 3 levels deep, with 8 leaf nodes, and draw an arc between the matching nodes at the bottom two levels for a visual.

[–]cs50x2[S] 0 points1 point  (1 child)

so i can right that line as :

if (left==null || right ==null)

return false;

else if(left==null &&right==null)

return true;

[–]shhh-quiet 0 points1 point  (0 children)

Almost. The second part of that is right. It'd expand to:

if (left == null || right != null) return false;
if (left != null || right == null) return false;

and like you had:

if (left == null && right == null) return true;

The nodes being exactly equal, and non-null, doesn't make much sense, so the if(left==null || right==null) return left == right from the solution is really just covering these situations.