Same Tree

题目:

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

判断两棵二叉树是否相等,相等的定义是树的结构一样且每个节点值相等

起先想着写个先序遍历然后把按先序把节点的值存到集合里,再将两个集合进行比对,结果行不通

因为树的结构不同输出的先序序列也可能是一样的 比方{10, 5, 15} 和 {10, 5, #, #, 15},这里用顺序存储表示树

public boolean isSameTree(TreeNode p, TreeNode q) {
		boolean result = false;
		if (p == null && q == null) {
        	return true;
        }
        if (p != null && q != null) {
        	result = p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right) ? true : false;
        }
        return result;
    }


树不相等的情况有很多,所以反过来想容易点,树相等的情况只有两棵树都是null或者当前节点值相等且左右子树均相等,其他都是false


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值