My Java solution recursion, easy to understand


  • 0
    A
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution 
    {
        public boolean isSameTree(TreeNode p, TreeNode q) 
        {
        	if(p == null && q == null)
        		return true;
        	else if((p == null && q != null) || (p != null && q == null))
        		return false;
        	else // in this case, both p and q are not null
        	{
        		// so we compare their value
        		if(p.val != q.val)
        			return false;
        		else // p.val == q. val, so we move forawrd to their children
        		{
        			boolean leftChildResult, rightChildResult;
        			leftChildResult = isSameTree(p.left, q.left);
        			rightChildResult = isSameTree(p.right, q.right);
        			return leftChildResult & rightChildResult; // only when both of their left and right subtree are same, this two trees are same.
        		}
        	}
        }       
    }
    

    However it only takes 0ms. There is sth wrong with the OJ.


Log in to reply
 

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