【 关关的刷题日记53】 Leetcode 100. Same Tree

时间:2022-05-08
本文章向大家介绍【 关关的刷题日记53】 Leetcode 100. Same Tree,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记53 – Leetcode 100. 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.

思路

思路:题目要求判断两棵树是否相等,那么我们要判断这两棵树对应节点的值是否相等,如果相等的话再进一步判断左右子树是否相等,判断左右子树是否相等的做法和判断两棵树是否相等是一样的,因此我们采用递归的做法。

class Solution {public:

    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p==nullptr && q==nullptr)
            return true;
        if(p==nullptr ||  q==nullptr)
            return false;
        if(p->val!=q->val)
            return false;
        else
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。