首页 > 代码库 > LeetCode:Same Tree

LeetCode: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.

解题思路:先判断当前根节点是否相同。如果都为空,则直接返回true。如果当前根节不为空且存储的值相同,则递归地判断左子树和右子树是否相同。其他情况返回false。

代码:

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



LeetCode:Same Tree