原题
检查两棵二叉树是否在通过若干次扭转后能够等价。扭转的定义是,交换任意节点的左右子树。等价的定义是,两棵二叉树必须为相同的结构,而且对应位置上的节点的值要相等。
注意:你能够假设二叉树中不会有重复的节点值。
样例ide
1 1
/ / \
2 3 and 3 2
/ \
4 4
是扭转后可等价的二叉树。code
1 1
/ / \
2 3 and 3 2
/ /
4 4
就不是扭转后能够等价的二叉树。递归
解题思路
Recursion - 递归求解,分治的思路。
注意,题目中说的是通过若干次扭转后能够等价,因此不要忘记考虑彻底identical的状况,某一个节点的左右子树翻转一次对称,反转两次还原。get
文/Jason_Yuan(简书做者)
原文连接:http://www.jianshu.com/p/0623...io
public boolean isTweakedIdentical(TreeNode a, TreeNode b) { if (a == null && b == null) { return true; } if (a == null || b == null) { return false; } if (a.val != b.val){ return false; } //divide // boolean left = isTweakedIdentical(a.left, b.right); // boolean right = isTweakedIdentical(a.right, b.left); //注意,题目中说的是通过若干次扭转后能够等价,因此不要忘记考虑彻底identical的状况,某一个节点的左右子树翻转一次对称,反转两次还原。 boolean left = isTweakedIdentical(a.left, b.left) || isTweakedIdentical(a.left, b.right); boolean right = isTweakedIdentical(a.right, b.right) || isTweakedIdentical(a.right, b.left); //conquer // if (left != true || right != true){ // return false; // } // else{ // return true; // } return left && right; }