算法 101. Symmetric Tree

101. Symmetric Tree
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:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    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) {
        
    }
}

给一个二叉树,检查下是不是自我镜像的(围绕中间对称)。
解:
思路一:递归。递归去判断,当前节点的左节点是否与右节点相同,不同返回 false。
思路二:遍历或者叫迭代。和递归差不多,只不过不是使用递归的方式。
思路三:旋转。这是我一刚开始的想法, 不停递归旋转左右子树,再去判断与原树是否相同,这复杂度还不如直接判断。

以下为代码:
递归方式:

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);
}

迭代方式:

public boolean isSymmetric(TreeNode root) {
    Queue<TreeNode> q = new LinkedList<>();
    q.add(root);
    q.add(root);
    while (!q.isEmpty()) {
        TreeNode t1 = q.poll();
        TreeNode t2 = q.poll();
        if (t1 == null && t2 == null) continue;
        if (t1 == null || t2 == null) return false;
        if (t1.val != t2.val) return false;
        q.add(t1.left);
        q.add(t2.right);
        q.add(t1.right);
        q.add(t2.left);
    }
    return true;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 目录 简书的 markdown 都不支持 [TOC] 语法……我就不贴目录了。下面按照类别,列出了29道关于二叉树...
    被称为L的男人阅读 3,379评论 0 8
  • 总结类型: 完全子树(#222) BST(左右子树值的性质,注意不仅要满足parent-child relatio...
    __小赤佬__阅读 724评论 0 0
  • 1. Binary Tree Preorder Traversal Description Given a bin...
    BookThief阅读 629评论 0 0
  • Validate Binary Search Tree Same Tree (基础) 101.symmetric ...
    lifesmily阅读 325评论 0 0
  • 说起小时候,真是一段快乐和幸福的日子。 我出生在安徽的一个小村子里,上小学之前,我的思维都活跃在那里,以为世界就那...
    isaky阅读 294评论 9 5