Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
method 1
这道题一开始思路就往复杂的方向思考,导致写的几个版本都有问题。看了答案之后发现自己把问题复杂化了
既然是对称的树,那么可以“复制”一下所给树root1,得到另一颗完全一样的树root2,root1往左遍历的时候,root2相应地往右遍历,这样就可以验证是否为对称树
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val)
&& isMirror(t1.right, t2.left)
&& isMirror(t1.left, t2.right);
}
更详细解释:https://leetcode.com/problems/symmetric-tree/solution/
summary
- 对称问题,可以通过复制本身,然后分别从不同方向遍历来解决!