问题描述:
100. 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。如果两棵树均为非空,则判断其中根节点是否相同,以及根节点的两棵左右子树是否相同。
代码展示:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
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;
//判断父节点是否相等,及其左右子树是否相等
return (p->val==q->val)&&(isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
}
};