Skip to content

Commit a980a2a

Browse files
committed
2022-05-19 update: added "Flip Equivalent Binary Trees"
1 parent 9b802ef commit a980a2a

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
4+
5+
// https://leetcode.com/problems/flip-equivalent-binary-trees
6+
public class FlipEquivalentBinaryTrees {
7+
8+
private final TreeNode root1;
9+
private final TreeNode root2;
10+
11+
public FlipEquivalentBinaryTrees(TreeNode root1, TreeNode root2) {
12+
this.root1 = root1;
13+
this.root2 = root2;
14+
}
15+
16+
public boolean solution() {
17+
return countFlipEquivalents(root1, root2);
18+
}
19+
20+
private boolean countFlipEquivalents(TreeNode root1, TreeNode root2) {
21+
if (root1 == root2) {
22+
return true;
23+
}
24+
if (root1 == null || root2 == null || root1.val != root2.val) {
25+
return false;
26+
}
27+
boolean original = countFlipEquivalents(root1.right, root2.right) && countFlipEquivalents(root1.left, root2.left);
28+
boolean switched = countFlipEquivalents(root1.right, root2.left) && countFlipEquivalents(root1.left, root2.right);
29+
return original || switched;
30+
}
31+
32+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.assertTrue;
7+
8+
public class FlipEquivalentBinaryTreesTest {
9+
10+
@Test
11+
public void defaultTest() {
12+
assertTrue(
13+
new FlipEquivalentBinaryTrees(
14+
new TreeNode(
15+
1,
16+
new TreeNode(
17+
2,
18+
new TreeNode(4),
19+
new TreeNode(
20+
5,
21+
new TreeNode(7),
22+
new TreeNode(8)
23+
)
24+
),
25+
new TreeNode(
26+
3,
27+
new TreeNode(6),
28+
null
29+
)
30+
),
31+
new TreeNode(
32+
1,
33+
new TreeNode(
34+
3,
35+
null,
36+
new TreeNode(6)
37+
),
38+
new TreeNode(
39+
2,
40+
new TreeNode(4),
41+
new TreeNode(
42+
5,
43+
new TreeNode(8),
44+
new TreeNode(7)
45+
)
46+
)
47+
)
48+
).solution()
49+
);
50+
}
51+
52+
}

0 commit comments

Comments
 (0)