L100 Same Tree + L101 Symmetric Tree = niu a niu

binary tree niu a niu

Problem: tweaked-identical-binary-tree

Check two given binary trees are identical or not. Assuming any number of tweaks are allowed. A tweak is defined as a swap of the children of one node in the tree.

  • Example

    1             1
   / \           / \
  2   3   and   3   2
 /                   \
4                     4
are identical.
    1             1
   / \           / \
  2   3   and   3   4
 /                   \
4                     2
are not identical.

Solution:

public boolean niuAniu(TreeNode left, TreeNode right){
    if(left == null && right == null) return true;
    if(left == null || right == null) return false;
    if(left.val != right.val) return false;

    return niuAniu(left.left,right.left) && niuAniu(left.right, right.right) || niuAniu(left.left, right.right) && niuAniu(left.right, right.left);
}

Last updated

Was this helpful?