Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Runtime: 0 ms, faster than 100.00% of Java online submissions for Flip Equivalent Binary Trees.
- class Solution {
- public boolean flipEquiv(TreeNode root1, TreeNode root2) {
- if (root1 == null && root2 == null) return true;
- if ((root1 == null) != (root2 == null)) return false;
- if (root1.val != root2.val) return false;
- TreeNode smallerChild1 = smaller(root1.left, root1.right);
- TreeNode smallerChild2 = smaller(root2.left, root2.right);
- if (!flipEquiv(smallerChild1, smallerChild2)) return false;
- TreeNode biggerChild1 = root1.left == smallerChild1 ? root1.right: root1.left;
- TreeNode biggerChild2 = root2.left == smallerChild2 ? root2.right: root2.left;
- return flipEquiv(biggerChild1, biggerChild2);
- }
- private TreeNode smaller(TreeNode a, TreeNode b) {
- if (a == null || b == null) return null;
- return a.val < b.val ? a: b;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement