码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Same Tree

时间:2014-10-24 13:03:03      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   

问题描述:

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

标签:algorithm   leetcode   

原文地址:http://blog.csdn.net/yao_wust/article/details/40425255

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!