470. Tweaked Identical Binary Tree
Check two given binary trees are identical or not. Assuming any number of tweaksare allowed. A tweak is defined as a swap of the children of one node in the tree.
Example
Example 1:
Input:{1,2,3,4},{1,3,2,#,#,#,4}
Output:true
Explanation:
1 1
/ /
2 3 and 3 2
/
4 4
are identical.
Example 2:
Input:{1,2,3,4},{1,3,2,4}
Output:false
Explanation:
1 1
/ /
2 3 and 3 2
/ /
4 4
are not identical.
Challenge
O(n) time
Notice
There is no two nodes with the same value in the tree.
思路:
tweaked identical tree 有两种情况,一种是b树是a树的tweak树(每个对应结点都交换),二是b树和a树完全相同。这两种情况为true。
思路和Lintcode469 Same tree相似,只是多一种组合。
代码:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param a: the root of binary tree a. * @param b: the root of binary tree b. * @return: true if they are tweaked identical, or false. */ public boolean isTweakedIdentical(TreeNode a, TreeNode b) { if (a == null && b == null) { return true; } else if (a != null && b != null) { return (a.val == b.val && isTweakedIdentical(a.left, b.left) && isTweakedIdentical(a.right, b.right)) ||(a.val == b.val && isTweakedIdentical(a.left, b.right) && isTweakedIdentical(a.right, b.left)); } else { return false; } } }