Same Tree: Recursive AND Return

Jay·2022년 5월 29일
0

Grind 120

목록 보기
25/38


First Thoughts: cannot return two boolean returns, and since we are only interested in whether there is at least one fault (different value or different structure -> when first tree has a value and the second tree has no value in the same corresponding position) we can use the && value of the return boolean. If at least one is false, the answer should give false. If both trees are null, should return true.

My Solution:

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

Catch Point:

  1. one way to encompass the two boolean return results could be to use the && operator on the two return values.

  2. repositioning of the conditional statements above could shorten solution (if we first check both are null), but not a big problem.

  3. think about the smaller problem. if confused whether both null case should return true or false, just think of the case where we are simply given two null trees.

0개의 댓글