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.
/*** Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
问题分析,简单的递归题,可以用先根遍历的递归算法,继续执行的判定标准是都空或都不空且值相同。
//code
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(p && q && p->val == q->val)
{
bool b = isSameTree(p->left, q->left);
if(b == false) return false;
return isSameTree(p->right, q->right);
}
if(q == NULL && p == NULL)
return true;
else return false;
}
};
说明:
bool b = isSameTree(p->left, q->left);
if(b == false) return false;
return isSameTree(p->right, q->right);
这三条语句可以合并为一条语句,但是这里写的麻烦是为了让看官们更清楚的理解这个层次,我们看下一条语句的写法:
return (isSameTree(p->left,q->left) && isSameTree(p->right, q->right));
其实是一样的,判断条件中的与操作是一种截断操作,即第一个条件为假,就不再判断以后的语句,直接返回判定结果。所以跟上面的本质是一致的,只不过要深入的挖掘下,这种层次感才能出来。