100 Same Tree

First Attempt

/**

  • 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) {
         return false;
     } else {
     // Here is a little tricky, I solve it for 3 times.
         if (p.val == q.val) {
             if (!isSameTree(p.left, q.left)) {
                 return false;
             } 
             if (!isSameTree(p.right, q.right)) {
                 return false;
             }
             return true;
         } else {
             return false;
         }
     }
    
    } }

Updated: precise one

/**

  • 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;
     }
     if ((p == null || q == null) || (p.val != q.val)) {
         return false;
     }
     return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    
    } }

Updated (12.19.15)

/**
 * 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 n1, TreeNode n2) {
        // forget return
        return helper(n1, n2);
    }
    private boolean helper(TreeNode n1, TreeNode n2) {
        if (n1 == null && n2 == null) {
            return true;
        }
        if (n1 == null || n2 == null) {
            return false;
        }
        return (n1.val == n2.val) && helper(n1.left, n2.left) && helper(n1.right, n2.right);
    }
}