-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsame-tree.java
38 lines (32 loc) · 930 Bytes
/
same-tree.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
ArrayDeque<Integer> pVal = new ArrayDeque<>();
ArrayDeque<Integer> qVal = new ArrayDeque<>();
collectVal(p, pVal);
collectVal(q, qVal);
if(pVal.size() != qVal.size()) return false;
while(pVal.size() > 0){
if(pVal.removeLast().intValue() != qVal.removeLast().intValue())
return false;
}
return true;
}
public void collectVal(TreeNode n, ArrayDeque<Integer> stock){
if(n == null) {
stock.addFirst(Integer.MAX_VALUE);
return ;
}
stock.addFirst(n.val);
collectVal(n.left, stock);
collectVal(n.right, stock);
}
}