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.

方法:

就是简单的递归,不知道我的代码哪里出问题了,一直通不过,看大神实现,发现了更简洁的写法

C++代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
        if(p == NULL || q == NULL)
            return p == q;
        if(q->val != p->val)
            return false;
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,162评论 0 10
  • 有三个不找:搞销售的不找,公务员不找,单亲不找。 搞销售的成年累月在外,以后家里你是既当爹又当娘。而且,搞销售的就...
    缺心眼子429阅读 2,662评论 0 1
  • 简单说一下学习okhttp的理由 google在Android 6.0中删除了HttpClient的Api,采用的...
    肖赛Soaic阅读 11,434评论 9 70
  • 1、很多人说,我怎么样才能判断一个上司是否是好上司?你看看他是否酷爱阅读和健身,喜欢阅读的人,视野格局一般不会太差...
    嬉笑怒骂皆生活阅读 975评论 0 0
  • 今天碰到一个需求就是 后台返回一串字符串是 @“1,你好你好你好年后;2你好你好年后你好你好;3你好哈你好呢你好呢...
    爱哭的僵小鱼阅读 11,713评论 1 9