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

第一种方法:不使用递归

只要保证根节点下的左子树的每一层是右子树的镜像,就可以说明此树是其自身的镜像

思路:用两个队列饭别记录左右子树每一层的节点,在广度优先遍历左右子树时,为了方便比较左右两边的节点,也把空节点加入到队列中。针对两边镜像节点的情况,必须处理如下不同的情况

(1)如果两边节点均为空,忽略这种情况;

(2)如果一边为空而另一边不为空,则返回false;

(3)如果两者均不为空,但值不相同,则返回false;

(4)除了以上三种情况。第四种情况为把左边的节点的子节点按照从左到右顺序加入到左边的队列尾部,而把右边的节点的子节点按照从右到左顺序加入到右边的队列尾部。其理由是方便用从头部到尾部的顺序比较两个队列是否为镜像关系、

在广度优先遍历完成之后,还需要判断两个队列是否均为空,只有均为空才返回真

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
    if (root == null) return true;
		//使用两个队列分别记录左右子树的每一层节点
		Queue<TreeNode> left = new LinkedList<TreeNode>();
		Queue<TreeNode> right = new LinkedList<TreeNode>();
		left.add(root.left);
		right.add(root.right);
		while (!left.isEmpty() && !right.isEmpty()) {
			//将两个队列的头部列出
			TreeNode l = left.poll();
			TreeNode r = right.poll();
			//忽略两者为空的情况
			if (l == null && r == null) {
				continue;
			}
			//一方为空,返回false
			if (l == null || r == null) {
				return false;
			}
			if (l.val != r.val) {
				return false;
			}
			left.add(l.left);
			left.add(l.right);
			//反过来插入
			right.add(r.right);
			right.add(r.left);
		}
		//遍历完之后,比较两队列的元素个数
		if (left.isEmpty() && right.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}
}


第二种方法:使用递归

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);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值