public boolean isSameTree(TreeNode p, TreeNode q) {
// Start typing your Java solution below
// DO NOT write main() function
if(p == null && q == null) {
return true;
}else if(p == null || q == null) {
return false;
}else {
if(p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
public boolean isSameTree(TreeNode p, TreeNode q) {
// Start typing your Java solution below
// DO NOT write main() function
if(p == null && q == null) {
return true;
}else if(p == null || q == null) {
return false;
}
Stack<TreeNode> sp = new Stack<TreeNode>();
Stack<TreeNode> sq = new Stack<TreeNode>();
sp.push(p);
sq.push(q);
while(!sp.empty() && !sq.empty()) {
p = sp.pop();
q = sq.pop();
if(p.val != q.val) return false;
if(p.right != null && q.right != null) {
sp.push(p.right);
sq.push(q.right);
}else if(p.right == null || q.right == null) {
if(!(p.right == null && q.right == null)) return false;
}
if(p.left != null && q.left != null) {
sp.push(p.left);
sq.push(q.left);
}else if(p.left == null || q.left == null) {
if(!(p.left == null && q.left == null)) return false;
}
}
if(sp.empty() && sq.empty()) return true;
return false;
}