您的位置:首页 > 其它

Leet Code 100 Same Tree

2015-11-22 16:47 519 查看


Same Tree

Question

Total Accepted: 94258 Total
Submissions: 224120 Difficulty: Easy

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.

Subscribe to see which companies asked this question

Show Tags

11

如果两棵树都为空,那么应该是相同的.

如果两棵树一棵为空,一棵树非空,那么是不同的

如果两棵树都不为空,但是根节点的值不同,那么两棵树不同

如果两个树根节点数据相同,就递归判断它们的左子树和又子树是否都相同.

/**
* 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&&!q)
return true;
if(!p&&q||!q&&p||p->val!=q->val)
return false;
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: