LeetCode100-相同的树

LeetCode100-相同的树

层序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) return true;
Queue<TreeNode> queue1 = new LinkedList<>();
Queue<TreeNode> queue2 = new LinkedList<>();
queue1.offer(p);
queue2.offer(q);
while (!queue1.isEmpty() && !queue2.isEmpty()) {
TreeNode poll1 = queue1.poll();
TreeNode poll2 = queue2.poll();
if (poll1.val != poll2.val) return false;
if (poll1.left == null ^ poll2.left == null) {
return false;
}
if (poll1.right == null ^ poll2.right == null) {
return false;
}
if (poll1.left!=null) queue1.offer(poll1.left);
if (poll2.left!=null) queue2.offer(poll2.left);
if (poll1.right!=null) queue1.offer(poll1.right);
if (poll2.right!=null) queue2.offer(poll2.right);

}
return true;
}