-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSameTree.java
More file actions
37 lines (32 loc) · 1.1 KB
/
Copy pathSameTree.java
File metadata and controls
37 lines (32 loc) · 1.1 KB
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
import java.util.ArrayList;
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) {
return (p == null && q == null);
}
ArrayList<Integer> pList = getValues(p, new ArrayList<>());
pList.add(p.val);
ArrayList<Integer> qList = getValues(q, new ArrayList<>());
qList.add(q.val);
if (pList.size() != qList.size()) {
return false;
}
for (int i = 0; i < pList.size(); i++) {
if (pList.get(i) != qList.get(i)) {
return false;
}
}
return true;
}
private ArrayList<Integer> getValues(TreeNode node, ArrayList<Integer> nodeList) {
if (node == null) {
return nodeList;
}
nodeList.add(node.left == null ? null : node.left.val);
nodeList.add(node.right == null ? null : node.right.val);
if (node.left != null && node.right == null) {
nodeList.remove(nodeList.size()-1);
}
return getValues(node.right, getValues(node.left, nodeList));
}
}