-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.java
83 lines (59 loc) · 1.99 KB
/
Solution.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
78
79
80
81
82
83
import java.util.Stack;
public class Solution {
private static class TreeNode {
TreeNode left;
TreeNode right;
int val;
TreeNode(int val) {
this.val = val;
}
}
private static boolean compareStructure(TreeNode rootS, TreeNode rootT) {
Stack<TreeNode> stackS = new Stack<>();
Stack<TreeNode> stackT = new Stack<>();
stackS.push(rootS);
stackT.push(rootT);
while (!stackS.isEmpty() && !stackT.isEmpty()) {
TreeNode s = stackS.pop();
TreeNode t = stackT.pop();
if (s == null && t != null)
return false;
if (t == null && s != null)
return false;
if (s == null && t == null)
continue;
if (s.val != t.val)
return false;
stackS.push(s.left);
stackS.push(s.right);
stackT.push(t.left);
stackT.push(t.right);
}
return stackS.isEmpty() && stackT.isEmpty();
}
private static boolean hasSameStructure(TreeNode rootS, TreeNode rootT) {
if (rootS == null)
return false;
if (hasSameStructure(rootS.right, rootT))
return true;
if (hasSameStructure(rootS.left, rootT))
return true;
return compareStructure(rootS, rootT);
}
public static void main(String[] args) {
TreeNode s1 = new TreeNode(1);
s1.left = new TreeNode(2);
TreeNode t1 = new TreeNode(1);
t1.left = new TreeNode(2);
System.out.println(hasSameStructure(s1, t1)); // true
TreeNode s2 = new TreeNode(1);
s2.left = new TreeNode(2);
s2.right = new TreeNode(2);
s2.right.right = new TreeNode(2);
s2.right.left = new TreeNode(2);
TreeNode t2 = new TreeNode(2);
t2.right = new TreeNode(2);
t2.left = new TreeNode(2);
System.out.println(hasSameStructure(s2, t2)); // true
}
}