Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isSameTree(TreeNode p, TreeNode q) { 12 // Start typing your Java solution below 13 // DO NOT write main() function 14 if((p == null) && (q == null)){ 15 return true; 16 } else if((p != null) && (q != null)){ 17 return cmp(p, q); 18 } else { 19 return false; 20 } 21 22 } 23 24 public boolean cmp(TreeNode p, TreeNode q){ 25 if(p.val != q.val){ 26 return false; 27 } 28 29 TreeNode pl = p.left, pr = p.right; 30 TreeNode ql = q.left, qr = q.right; 31 32 if(((pl == null) && (ql != null)) || ((pl != null) && (ql == null))){ 33 return false; 34 } 35 36 if(((pr == null) && (qr != null)) || ((pr != null) && (qr == null))){ 37 return false; 38 } 39 boolean lFlag = true; 40 boolean rFlag = true; 41 if((pl != null) && (ql != null)){ 42 lFlag = cmp(pl, ql); 43 } 44 if((pr != null) && (qr != null)){ 45 rFlag = cmp(pr, qr); 46 } 47 return lFlag && rFlag; 48 } 49 }