给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3]
是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
思路与代码
递归法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return isSymmetricCore(root.left, root.right);
}
public boolean isSymmetricCore(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) return true;
if (root1 == null || root2 == null) return false;
if (root1.val != root2.val) return false;
return isSymmetricCore(root1.left, root2.right) && isSymmetricCore(root1.right, root2.left);
}
}
迭代法
从下图可以看出,中序遍历结果是回文的,通过迭代法进行中序遍历,再判断回文即可。
1
/ \
2 2
/ \ / \
3 4 4 3