Description:
Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1:
Input:
1 |
|
Output: true
Example 2:1
2
3
4
5
6Input:
1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input:1
2
3
4
5 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
解法:
相对而言比较简单的题,对于树做遍历,我这里采用的是按层遍历,对比每一个元素判断是否相同。采用的Java的队列,因为队列为空不好判断(下回用Stack可能会好一点),这里采用了虚拟节点(也算是撞对了吧0.0)。代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Queue<TreeNode> queuep = new LinkedList<TreeNode>();
Queue<TreeNode> queueq = new LinkedList<TreeNode>();
queuep.offer(p);
queueq.offer(q);
while (queuep.peek() != null && queueq.peek() != null) {
TreeNode tmp1 = queuep.poll();
TreeNode tmp2 = queueq.poll();
if (tmp1.val == tmp2.val) {
if (tmp1.val == -32767) {
continue;
} else {
if (tmp1.left != null) {
queuep.offer(tmp1.left);
} else {
queuep.offer(new TreeNode(-32767));
}
if (tmp1.right != null) {
queuep.offer(tmp1.right);
} else {
queuep.offer(new TreeNode(-32767));
}
if (tmp2.left != null) {
queueq.offer(tmp2.left);
} else {
queueq.offer(new TreeNode(-32767));
}
if (tmp2.right != null) {
queueq.offer(tmp2.right);
} else {
queueq.offer(new TreeNode(-32767));
}
}
} else {
return false;
}
}
if (queuep.peek() == null && queueq.peek() != null) {
return false;
} else if (queueq.peek() == null && queuep.peek() != null) {
return false;
} else {
return true;
}
}
}
除了借用队列以外,其实还可以采用深度优先搜索的递归方法进行比较,代码如下:1
2
3
4
5
6
7
8class Solution {
public:
bool isSameTree(TreeNode \*p, TreeNode \*q) {
if (!p && !q) return true;
if ((p && !q) || (!p && q) || (p->val != q->val)) return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};