检测对称二叉树

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

例如,二叉树 [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

说明:

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


递归方式:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
		if(root == null) {
			return true;
		}
		return r(root.left, root.right);
    }
    public boolean r(TreeNode ml, TreeNode mr) {
		if (ml == null && mr == null) {
			return true;
		}
		if (ml == null || mr == null) {
			return false;
		}
		if (ml.val != mr.val) {
			return false;
		}
		return r(ml.left, mr.right) && r(ml.right, mr.left);
	}
}

迭代方式:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
		
		if (root == null) {
			return true;
		}
		LinkedList<TreeNode> tLCur = new LinkedList<TreeNode>();
		LinkedList<TreeNode> tLNex = new LinkedList<TreeNode>();
		LinkedList<TreeNode> tRCur = new LinkedList<TreeNode>();
		LinkedList<TreeNode> tRNex = new LinkedList<TreeNode>();

		tLNex.add(root.left);
		tRNex.add(root.right);

		while (true) {
			if (tLNex.size() != tRNex.size()) {
				return false;
			}
			if (tLNex.size() == 0) {
				return true;
			}
			tLCur = tLNex;
			tLNex = new LinkedList<TreeNode>();
			tRCur = tRNex;
			tRNex = new LinkedList<TreeNode>();

			do {
				TreeNode tl = tLCur.removeFirst();
				TreeNode tr = tRCur.removeLast();
				if(tl==null && tr==null) {
					continue;
				}
				if(tl==null || tr==null) {
					return false;
				}
				if(tl.val!=tr.val) {
					return false;
				}
				tLNex.add(tl.left);
				tLNex.add(tl.right);
				tRNex.push(tr.right);
				tRNex.push(tr.left);
			} while (tLCur.size() > 0);
		}
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

horo99

求个赞啦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值