My accepted JAVA clean 5-line recursive code


  • 1
    V
    if (p == null && q == null) return true;
    if (p == null || q == null) return false; // if one of them are not null, both of them cannot be null.
    if (p.val != q.val) return false;
    if (isSameTree(p.left, q.left) == false || isSameTree(p.right, q.right) == false) return false;
    return true;
    

    Very straight forward, check from top to down, bot are not null or both are null -> same value -> same child.
    If any of the criteria fails, return false. Otherwise, If the node pass all the checking, return true.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.