LeetCode(101):对称二叉树 Symmetric Tree(Java)

234 篇文章 1 订阅
177 篇文章 0 订阅

2019.8.2 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

递归的思路很简单,递归比较左子树的右子树&右子树的左子树、左子树的左子树和右子树的右子树即可,看起来比较绕,写起来思路还是很清晰的。

迭代的思路是用层序遍历的方法,但是需要做个小调整。

调整1:每次弹出两个结点用于比较。

调整2:压入顺序为左子树的右子树、右子树的左子树、左子树的左子树、右子树的右子树。

比较思路基本和递归相同。有个小tip是在第一次在递归函数的入参或迭代队列初始化时,放入根节点的左右子结点可以改为放入两个根节点。此举可以省去判断根节点为空的情况。


传送门:对称二叉树

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

Note:Bonus points if you could solve it both recursively and iteratively.

给定一个二叉树,检查它是否是镜像对称的。

说明: 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

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

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
    1
   / \
  2   2
   \   \
   3    3


import java.util.LinkedList;

/**
 *
 * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
 * Note: Bonus points if you could solve it both recursively and iteratively.
 * 给定一个二叉树,检查它是否是镜像对称的。
 * 说明: 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
 *
 */

public class SymmetricTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    //递归法
    public boolean isSymmetric(TreeNode root) {
        //return root == null || Solution(root.left, root.right);
        return Solution(root, root);
    }

    public boolean Solution(TreeNode left, TreeNode right){
        if(left == null && right == null){
            return true;
        }
        if(left == null || right == null){
            return false;
        }
        return left.val == right.val && Solution(left.right, right.left) && Solution(left.left, right.right);
    }

    //迭代法:模拟层序遍历,每提取两个结点后按相反的顺序放入队列
    public boolean isSymmetric2(TreeNode root){
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        queue.add(root);
        /*
        if(root == null){
            return true;
        }
        queue.add(root.left);
        queue.add(root.right);
        */
        while(!queue.isEmpty()){
            TreeNode left = queue.pop();
            TreeNode right = queue.pop();
            if(left == null && right == null){
                continue;
            }
            if(left == null || right == null || left.val != right.val){
                return false;
            }
            queue.add(left.left);
            queue.add(right.right);
            queue.add(left.right);
            queue.add(right.left);
        }
        return true;
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值