same-tree

作者: 美不胜收oo | 来源:发表于2018-12-19 21:54 被阅读0次

描述:

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);
    }
};

相关文章

网友评论

    本文标题:same-tree

    本文链接:https://www.haomeiwen.com/subject/lybskqtx.html