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.
题意为:判断两棵二叉树是否一样。
C代码实现accepted。思路:暴力比较,代码个人觉得写的不够简洁。先比较根节点,然后左右子树。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode *p, struct 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!=NULL && q!=NULL && p->val != q->val) return false;
else
return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
}