【剑指Offer学习】【题58:对称的二叉树】

题目:
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

思路:
使用递归的方式进行了比较,另外这里的对称,是说镜像相同。而镜像与原来的是反的。即左子树的左子树与右子树的右子树相同。
1、结点为空时,返回true;
2、比较左右子结点的值:
①当对应左右子结点都为空时,返回true;
②当对应左右子结点/一个为空,一个不为空时,说明树不对称,则返回false;
③当对应左右子结点的值相等时,使用递归,对下一对结点进行判断。

程序:

class TreeNode{
	int val = 0;
	TreeNode left = null;
	TreeNode right = null;
	TreeNode(int val){
		this.val = val;
	}
}
public class subject58 {
	public static boolean isSymmetrical(TreeNode pRoot) {
		if(pRoot == null) {
			return true;
		}
		return isSymmetrical(pRoot, pRoot);
	}
	public static boolean isSymmetrical(TreeNode root1, TreeNode root2) {
	//比较左右子结点
		if(root1 == null && root2 == null) {//全为空时,返回true
			return true;
		}else if(root1 == null || root2 == null){//一个为空,一个不为空时,返回false
			return false;
		}else if(root1.val == root2.val){
			return isSymmetrical(root1.left, root2.right) && isSymmetrical(root1.right, root2.left);
		}
		return false;
	}
	public static void main(String args[]) {
		TreeNode root = new TreeNode(1);
		root.left = new TreeNode(2);
        root.right = new TreeNode(2);
        //root.left.left = new TreeNode(4);
        //root.left.right = new TreeNode(5);
        System.out.println(isSymmetrical(root));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值