Recursive simple java solution, 0ms


  • 0
    M

    The idea is simple, at a moment compare the current node value of both the trees and then compare their left and right subtrees recursively.
    PS: Improvements and suggestions will be appreciated.

    public class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            //If both are null, it means that their structure is identical so far. So return true.
            if( p == null && q == null )
                return true;
            //If both are not null, check the root value and check whether their left and right sub-trees are identical.
            else if( p != null && q != null )
            {
                if( p.val == q.val)
                    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
                //return false, if the values are not same.
                else
                    return false;
            }
            //If only one node is null and not the other.
            else
                return false;
        }
    }
    

Log in to reply
 

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