Leetcode——101. Symmetric Tree(非递归方法)

题目原址

https://leetcode.com/problems/symmetric-tree/description/

题目描述

Pick One

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.

解题思路

给定一个二叉树,判断该二叉树是否是对称的,对称的含义是:同一层上的元素,第一个元素和最后一个元素相等,第二个元素和倒数第二个元素相等

这里我采用的是队列的方式按层遍历数组,非递归的方法,将数组中的每一行元素添加的队列中,如果节点没有左或者右孩子,则将其左或者右孩子的值置为Integer.MAX_VALUE,其实这个只是因为OJ没有那么多测试用例,偷个懒使用数组存储每一行数据,因为数组不能存null,所以将null存为Integer.MAX_VALUE,这里可以使用其他的能够存储null的数据结构存储每一行数据。

AC代码

class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if(root == null)
            return true;
        queue.add(root);
        while(queue.size() > 0) {
            int size = queue.size();
            int[] arr = new int[size];
            int index = 0;
            for(int i = 0; i < size; i++) {
                TreeNode tn = queue.poll();
                if(tn == null)
                    arr[index ++] = Integer.MAX_VALUE;
                else{
                    arr[index ++] = tn.val;
                    if(tn.left != null)
                        queue.add(tn.left);
                    else
                        queue.add(null);
                    if(tn.right != null)
                        queue.add(tn.right);
                    else
                        queue.add(null);
                }
            }
            int left = 0, right = size - 1;
            while(left < right) {
                if(arr[left] == arr[right]){
                    left ++; right--;
                }else
                    return false;
            }
        }
        return true;  
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值