好久没来leetcode上面做题了,今天先从一道简单题目来熟悉一下先。题目是Same Tree描述如下:
<span style="font-size:12px;">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.</span>
题目其实很简单,就是要看给的两颗二叉树是不是一样的(即结构上和对应结点上的值一样)。这个题目拿到手第一种想法就是递归遍历,分别判断对应位置的值是否相等,如果相等就继续递归判断左右儿子,如果不等,直接返回false就可以了。
下面直接上代码:
//判断结点上的值是否相等
bool isSameValue(TreeNode *p,TreeNode *q)
{
if(p != NULL && q != NULL && p->val == q->val)
{
return true;
}
else if (p == NULL && q == NULL)
{
return true;
}
else
{
return false;
}
}
//判断是不是同一棵树的递归函数
bool isSameTree(TreeNode *p, TreeNode *q)
{
if (p == NULL && q == NULL)
{
return true;
}
if (isSameValue(p,q))
{
//如果该结点上的值相等,那么就递归其左右儿子结点
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
else
{
return false;
}
}
其实就是几行代码,非常简单。就不多说了。