LeetCode--same tree(C++)

题目描述: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.

翻译:给定两个二叉树,编写一个函数来检查它们是否相等。
如果两个二叉树具有相同的结构,并且所有节点具有相同的值,则被认为是相等的。

思路分析:最近做了很多二叉树的相关题目,我们都要记住一个思想–递归。
分为三种情况:
(1)两颗树都为空,返回真;
(2)两颗二叉树一颗为空,一颗不为空,返回假;
(3)两颗二叉树的根节点相等,并且左子树和右子树也相等,返回真,否则返回假。

代码实现:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TeeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) 
    {
        if(p==NULL && q==NULL)
            return true;

        if(p==NULL || q==NULL)
            return false;

        return p->val==q->val && isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
    }
};

猜你喜欢

转载自blog.csdn.net/cherrydreamsover/article/details/81806847