给你一个二叉树的根节点 root , 检查它是否轴对称。

    示例 1:
    image.png

    输入:root = [1,2,2,3,4,4,3]
    输出:true
    示例 2:

    输入:root = [1,2,2,null,3,null,3]
    输出:false

    提示:

    树中节点数目在范围 [1, 1000] 内
    -100 <= Node.val <= 100

    进阶:你可以运用递归和迭代两种方法解决这个问题吗?


    1. class Solution {
    2. public boolean isSymmetric(TreeNode root) {
    3. return dfs(root.left, root.right);
    4. }
    5. private boolean dfs(TreeNode left, TreeNode right) {
    6. if (left == null && right != null || left != null && right == null) return false;
    7. if (left == null && right == null) return true;
    8. if (left.val != right.val) return false;
    9. return dfs(left.left, right.right) && dfs(left.right, right.left);
    10. }
    11. }

    迭代

    1. class Solution {
    2. public boolean isSymmetric(TreeNode root) {
    3. Deque<TreeNode> q = new LinkedList<>();
    4. q.addLast(root.left);
    5. q.addLast(root.right);
    6. while (!q.isEmpty()) {
    7. TreeNode a = q.pollFirst();
    8. TreeNode b = q.pollFirst();
    9. if (a == null && b != null || a != null && b == null) return false;
    10. if (a == null && b == null) continue;
    11. if (a.val != b.val) return false;
    12. q.addLast(a.left);
    13. q.addLast(b.right);
    14. q.addLast(a.right);
    15. q.addLast(b.left);
    16. }
    17. return true;
    18. }
    19. }