Solution by kyramae


  • 0
    K

    Algorithm

    1. First, check if both of the nodes are null. If yes, then we're sure that they are equal and there are no further child nodes to check.
    2. Next, check if the both nodes are not null. If one of them is null then we are sure that they don't have the same value.
    3. Finally, check if the value of the nodes are the same. If they are, then we need to further check the equality of its right and left nodes by recursively calling the method isSameTree. They can only be considered the same if both right nodes and left nodes are identical.
    class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            boolean isEqual = false;
            
            if(p==null && q==null) {
                isEqual=true;
            } else if(p!=null && q!=null && p.val==q.val) {
                if(isSameTree(p.right,q.right) && isSameTree(p.left,q.left)) {
                    isEqual = true;
                }
            }
            
            return isEqual;
        }
    }
    

Log in to reply
 

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