检查两棵二叉树是否在经过若干次扭转后可以等价。扭转的定义是,交换任意节点的左右子树。等价的定义是,两棵二叉树必须为相同的结构,并且对应位置上的节点的值要相等。
样例
例1:
输入:{1,2,3,4},{1,3,2,#,#,#,4}
输出:true
说明:
1 1
/ \ / \
2 3 和 3 2
/ \
4 4
是相同的。
例2:
输入:{1,2,3,4},{1,3,2,4}
输出:false
说明:
1 1
/ \ / \
2 3 和 3 2
/ /
4 4
不一样。
挑战
在 O(n) 的时间内完成。
注意事项
你可以假设二叉树中不会有重复的节点值。
解题思路:
判断值相等
取到 a的左右两边 取到b的左右二边
a的左边 必须等于b的右边 或者 等于左边
a的右边 必须等于b的左边 或者 等于右边
只有满足一种条件就是ok的
这样才是identical
/**
* 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) {
// write your code here
if(a == null && b == null)
return true;
if(a == null || b == null)
return false;
if(a.val != b.val)
return false;
return (isTweakedIdentical(a.left, b.left) && isTweakedIdentical(a.right, b.right)) || (isTweakedIdentical(a.left, b.right) && isTweakedIdentical(a.right, b.left));
}
}