Advertisement
ogv

Untitled

ogv
Nov 5th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.99 KB | None | 0 0
  1. // Runtime: 0 ms, faster than 100.00% of Java online submissions for Flip Equivalent Binary Trees.
  2. class Solution {
  3.     public boolean flipEquiv(TreeNode root1, TreeNode root2) {
  4.         if (root1 == null && root2 == null) return true;
  5.         if ((root1 == null) != (root2 == null)) return false;
  6.        
  7.         if (root1.val != root2.val) return false;
  8.        
  9.         TreeNode smallerChild1 = smaller(root1.left, root1.right);
  10.         TreeNode smallerChild2 = smaller(root2.left, root2.right);
  11.        
  12.         if (!flipEquiv(smallerChild1, smallerChild2)) return false;
  13.        
  14.         TreeNode biggerChild1 = root1.left == smallerChild1 ? root1.right: root1.left;
  15.         TreeNode biggerChild2 = root2.left == smallerChild2 ? root2.right: root2.left;
  16.        
  17.         return flipEquiv(biggerChild1, biggerChild2);
  18.     }
  19.    
  20.     private TreeNode smaller(TreeNode a, TreeNode b) {
  21.         if (a == null || b == null) return null;
  22.        
  23.         return a.val < b.val ? a: b;
  24.     }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement