前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:100. Same Tree

LeetCode笔记:100. Same Tree

作者头像
Cloudox
发布2021-11-23 14:11:11
1230
发布2021-11-23 14:11:11
举报
文章被收录于专栏:月亮与二进制月亮与二进制

题目:

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.

大意:

给出两个二叉树,写一个函数来检查两者是否相等。 所谓相等,是指他们结构相同且节点有同样的值。

思路:

这个思路还比较直接,考虑全面一点就好了。首先考虑节点为空的情况,如果两个都为空,那么直接相等;如果一个为空一个不为空,那么不相等;如果两个都不为空,那么继续进行深层次的判断。 首先看两个节点的值是否相等,不相等则二叉树不等,然后判断其子节点,这时候使用递归就可以了,对两个节点的左节点和右节点分别调用这个函数,只有都返回相等时,才表示两个节点完全相同,由于递归,其子节点也就一层层地判断下去了,整个二叉树就会遍历完成。

代码(Java):

代码语言:javascript
复制
/**
 * 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 isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p != null && q != null) {
            if (p.val != q.val) return false;
        
            if (isSameTree(p.left, q.left) && isSameTree(p.right, q.right)) return true;
            else return false;
        } else {
            return false;
        }
    }
}

其实还可以进一步精简代码,可以看下Discuss最火的代码,思路是一致的,只是精简到了极致,确实很赞:

精简代码(Java):

代码语言:javascript
复制
/**
 * 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 isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null || q == null) return false;
        if(p.val == q.val)
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        return false;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目:
  • 大意:
  • 思路:
  • 代码(Java):
  • 精简代码(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档