4
\$\begingroup\$

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

Tree is defined as :

 /**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */

And my solution is

public boolean isSameTree(TreeNode p, TreeNode q) {
 if(null == p && null == q){
 return true;
 }
 if((null == p && null != q) || (null == q && null != p)){
 return false;
 }
 if(p.val == q.val){
 return isSameTree(p.left,q.left) ? isSameTree(p.right,q.right) :false;
 } else {
 return false;
 }
}

Please suggest any improvements.

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Oct 30, 2017 at 6:06
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Your code already does its job well. It can be shortened a bit:

public boolean isSameTree(TreeNode p, TreeNode q) {
 if (p == null || q == null) {
 return p == q;
 }
 return p.val == q.val
 && isSameTree(p.left, q.left)
 && isSameTree(p.right, q.right);
}

I flipped the operands of the == operators since having null in the right hand side reads more naturally.

I added spaces after the if and after the commas to follow the common formatting style.

answered Oct 30, 2017 at 7:03
\$\endgroup\$
2
  • 1
    \$\begingroup\$ p == null && q == null can even be shorted to p == q in this case. \$\endgroup\$ Commented Oct 30, 2017 at 8:22
  • 1
    \$\begingroup\$ @RolandIllig shorter code is not always better. I could not immediately determine why the p==q is correct here. So I would either comment it in, or be more verbose. btw I do really like the && in the return statement. \$\endgroup\$ Commented Oct 30, 2017 at 14:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.