LeetCode101. 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.

尝试

自己的思路为,通过层次遍历的方法,将每一层的元素全部保存在一个链表里,包括该位置若没有节点,则保存null,然后每层对比对称位置元素。但是超时了,原因在于思路过于复杂,开销大。代码如下,请勿参考:

import java.util.LinkedList;
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        LinkedList<TreeNode> result = new LinkedList<TreeNode>();
        TreeNode p = root;
        int line1 = 1, line2 = 0;
        queue.offer(p);
        while (!queue.isEmpty()) {
            p = queue.pop();
            result.offer(p);
            if (p != null) {
                queue.offer(p.left);
                queue.offer(p.right);
            } else{
                queue.offer(null);
                queue.offer(null);
            }
            line2 += 2;
            if (--line1 == 0) {
                while (!result.isEmpty()) {
                    if ((result.getFirst() == null && result.getLast() == null) || (result.getFirst().val == result.getLast().val)){
                        result.removeFirst();
                        if (!result.isEmpty()){
                            result.removeLast();
                        }
                    } else {
                        return false; 
                    }
                }
                line1 = line2;
                line2 = 0;
                result.clear();
            }
        }
        return true;
    }
}

正确算法

参考LeetCode文档,思路为:由于要判断一棵树是不是镜像,即可以将问题转化为镜像的两棵树是不是相同,类似如图:

这里写图片描述

递归的思路
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值