LeetCode 集锦(二十二) - 第 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

 Note:
Bonus points if you could solve it both recursively and iteratively.
复制代码

翻译:

给定一个二叉树,检查它是不是自身的镜像(即围绕其中心对称)。 例如,这个二叉树[1,2,2,3,4,4,3]是对称的:git

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

复制代码

可是下面的[1,2,2,null,3,null,3]不是:github

1
  / \
 2   2
  \   \
  3    3
复制代码

注意: 若是你能递归地和迭代地解出它,那就更好了。bash


解题思路

本题判断两个树是否镜像树,镜像树的特色,在于它的左节点和右节点是同样的,根据这个特色咱们能够解决这个问题。ui

解题方法

  1. 按照思路代码以下this

    public boolean isSymmetric(TreeNode root) {
         if (root == null) {
             return true;
         }
    
         return isSymmetric(root.left, root.right);
    
     }
    
     public boolean isSymmetric(TreeNode left, TreeNode right) {
    
         if (left == null && right == null) {
             return true;
         }
    
         boolean isSame = left == null;
         isSame = isSame ? false : right != null && left.val == right.val;
    
         return isSame && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    
     }
    
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    
        TreeNode(int x) {
            val = x;
        }
    }
    
    复制代码

    时间复杂度: 该方案用了递归遍历树,不要判断时间复杂度,并且树的遍历复杂度都说很差,且记为 O(n)spa

    空间复杂度: 该方案使用了没有使用额外空间,因此空间复杂度是 O(n)=O(1);翻译

总结

本题的大体解法如上所诉,按照特色咱们能够很简单的解决这个问题,其实也能够按层进行对比,判断每一层是否镜像,能够用队列来解决。code

欢迎关注个人博客-FightCrap递归

相关文章
相关标签/搜索