深度优先搜索
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null)
return true;
if (p == null || q == null)
return false;
if (p.val != q.val)
return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
广度优先搜索
public boolean isSameTree1(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
} else if (p == null || q == null) {
return false;
}
Queue<TreeNode> q1 = new LinkedList<TreeNode>();
Queue<TreeNode> q2 = new LinkedList<TreeNode>();
q1.offer(p);
q2.offer(q);
while (!q1.isEmpty() && !q2.isEmpty())
{
TreeNode n1 = q1.poll();
TreeNode n2 = q2.poll();
if (n1 == null && n2 == null)
continue;
if (n1 == null ^ n2 == null) {
return false;
}
if (n1.val != n2.val)
return false;
q1.offer(n1.left);
q1.offer(n1.right);
q2.offer(n2.left);
q2.offer(n2.right);
}
return true;
}