Flip Equivalent Binary Trees LeetCode solution in Java

1
class Solution {
2
public boolean flipEquiv(TreeNode root1, TreeNode root2) {
3
return helper(root1, root2);
4
}
5

6
private boolean helper(TreeNode x, TreeNode y) {
7
if (x == null && y == null) return true;
8
if (x == null || y == null || x.val != y.val) return false;
9
boolean similarity =
10
helper(x.left, y.left) && helper(x.right, y.right); // check if 2 subtrees are similar
11
boolean swap =
12
helper(x.left, y.right)
13
&& helper(
14
x.right,
15
y.left); // check if the 2 subtrees can be similar after swapping the left & right
16
// subtrees with each other
17

18
return similarity || swap; // if either true, means we can flip to match both trees
19
}
20
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0