《剑指offer》非递归法判定二叉树是否是对称的

题目:请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

解析:该非递归法有点傻傻的,思想是利用队列进行层次遍历。然后翻转该二叉树,再层次遍历该二叉树,最后对比 两棵树的节点值是否一样的,一样的则是对称的,不一样的就不对称了。

import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    //二叉树镜像
    public  void reverseTree(TreeNode root){
        if(root==null){
            return ;
        }
        if(root.left!=null){
            reverseTree(root.left);
        }
        if(root.right!=null){
            reverseTree(root.right);
        }
        TreeNode temp=root.left;
        root.left=root.right;
        root.right=temp;
    }
    boolean isSymmetrical(TreeNode pRoot)
    {
        if(pRoot==null){
            return true;
        }
        //队列1存储
        TreeNode temp1;
        Queue<TreeNode> queue1 = new LinkedList<>();
        queue1.add(pRoot);
        List<Integer> list1 =new ArrayList<>();
        while(!queue1.isEmpty()){
            temp1=queue1.poll();
            list1.add(temp1.val);
            if(temp1.left!=null){
                queue1.add(temp1.left);
            }
            if(temp1.left==null){
                list1.add(-1);//左孩子为空,添加-1标识
            }
            if(temp1.right!=null){
                queue1.add(temp1.right);
            }
            if(temp1.right==null){
                list1.add(-2);//右孩子为空,添加-2标识
            }
        }
        reverseTree(pRoot);
        //队列2存储
        TreeNode temp2;
        Queue<TreeNode> queue2 = new LinkedList<>();
        queue2.add(pRoot);
        List<Integer> list2 =new ArrayList<>();
        while(!queue2.isEmpty()){
            temp2=queue2.poll();
            list2.add(temp2.val);
            if(temp2.left!=null){
                queue2.add(temp2.left);
            }
            if(temp2.left==null){
                list2.add(-1);
            }
            if(temp2.right!=null){
                queue2.add(temp2.right);
            }
            if(temp2.right==null){
                list2.add(-2);
            }
        }
        if(list1.equals(list2)){//比较两颗树的节点是否一样的
            return true;
        }
        else{
            return false;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值