-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution100.java
77 lines (68 loc) · 1.72 KB
/
Solution100.java
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package algorithm.leetcode;
import java.util.LinkedList;
/**
* @author: mayuan
* @desc: 相同的树
* @date: 2019/02/21
*/
public class Solution100 {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (null == p && null == q) {
return true;
}
if (null == p || null == q) {
return false;
}
if (p.val != q.val) {
return false;
} else {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
/**
* 非递归解法
*
* @param p
* @param q
* @return
*/
public boolean isSameTree2(TreeNode p, TreeNode q) {
if (null == p && null == q) {
return true;
}
if (null == p || null == q) {
return false;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(p);
queue.add(q);
while (!queue.isEmpty()) {
TreeNode a = queue.pollFirst();
TreeNode b = queue.pollFirst();
// 遍历到叶子节点
if (null == a && null == b) {
continue;
} else if (null == a || null == b) {
return false;
} else {
if (a.val != b.val) {
return false;
} else {
queue.addLast(a.left);
queue.addLast(b.left);
queue.addLast(a.right);
queue.addLast(b.right);
}
}
}
return true;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}