NO.100 相同的树

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入:       1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

输出: true

示例 2:

输入:      1          1
          /           \
         2             2

        [1,2],     [1,null,2]

输出: false

示例 3:

输入:       1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

输出: false

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

void DFS(struct TreeNode* p,struct TreeNode* q,bool *ret)
{
    if(*ret)
    {
        if((p&&!q)||(!p&&q))
        {
            *ret=false;
            return;
        }
        if(p&&q)
        {
            if(p->val!=q->val)
            {
                *ret=false;
                return;
            }
            else
            {
                DFS(p->left,q->left,ret);
                DFS(p->right,q->right,ret);
            }
        }
    }
}

bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    bool ret=true;
    DFS(p,q,&ret);
    return ret;
}

执行用时 : 0 ms, 在Same Tree的C提交中击败了100.00% 的用户

内存消耗 : 7 MB, 在Same Tree的C提交中击败了100.00% 的用户

猜你喜欢

转载自blog.csdn.net/xuyuanwang19931014/article/details/91385389