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

结果



猜你喜欢

转载自blog.csdn.net/sun10081/article/details/80780169