LeetCode:Same Tree - 判断两颗树是否相等

1、题目名称

Same Tree(判断两棵树是否相等)

2、题目地址

https://leetcode.com/problems/same-tree/

3、题目内容

英文: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.

中文:给定两颗二叉树,写一个函数判断这两棵树是否相等。如果两棵树的结构和各节点中保存的值是相等的,则认为这两棵树相等。

4、解题方法

本题可以采用先根遍历的方法,从上到下递归考察各节点。在任意一对节点的比较中,如果左右枝是否为空的属性和节点中的val值不相等,则认为两棵树不是同一棵树,否则继续考察。如果遍历结束后仍然不能证明这两棵树不是同一棵树,则这两棵树就是相等的

解决问题的Java代码如下:

/**
 * 功能说明:LeetCode 100 - Same Tree
 * 开发人员:Tsybius2014
 * 开发时间:2015年8月12日
 */
public class Solution {
    
    /**
     * 判断两个树是否为相等
     * @param p 树p
     * @param q 树q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (
            (p == null && q != null) || 
            (p != null && q == null) || 
            p.val != q.val || 
            !isSameTree(p.left, q.left) || 
            !isSameTree(p.right, q.right)) {
            return false;
        } else {
            return true;
        }
    }
}

END

转载于:https://my.oschina.net/Tsybius2014/blog/491629

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值