leetcode刷题之旅(101)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


思路分析

在比较相同二叉树(Same Tree)的基础上,更改了判断条件。

即 上题是先序遍历,比较每个节点的值,此题同样是遍历,却是左子树与右子树比较,左子树的左子树与右子树的右子树比较,右子树的左子树与左子树的右子树比较(说起来有些抽象,配合图看),满足条件即是对称二叉树



代码

方法一:递归

public boolean isSymmetric(TreeNode root) {
        return isSymmetric(root, root);  
    }
	public boolean isSymmetric(TreeNode root1,TreeNode root2){
		if (root1==null && root2==null) {  //都为空 即相等
			return true;
		}
		if (root1==null || root2==null) {  //任一为空 不满足条件 终止遍历
			return false;
		}
		if (root1.val == root2.val) {  //左子树与对应右子树比较,右子树同理,相等则继续遍历
			return isSymmetric(root1.left, root2.right) && isSymmetric(root1.right, root2.left);
		}
		return false;
	}

结果



方法二:循环写法 层序遍历

public boolean isSymmetric(TreeNode root) {
		return isSymmetric(root,root);
	}
	public boolean isSymmetric(TreeNode p,TreeNode q) {
		Queue<TreeNode> queue = new LinkedList<TreeNode>();
		 queue.offer(p);
		 queue.offer(q);
		 while ( !queue.isEmpty() ){
			 TreeNode temp1 = queue.poll();
			 TreeNode temp2 = queue.poll();
			 if (temp1==null && temp2==null) {
				continue;
			}
			 if (temp1==null || temp2==null || temp1.val != temp2.val) {
				return false;
			}
			 queue.offer(temp1.left);
			 queue.offer(temp2.right);
			 queue.offer(temp1.right);
			 queue.offer(temp2.left);
		 }
		return true;
	}

结果


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值