版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
检查两颗树是否相同
思路
- 根要相等 p->val == q->val
- 左子树相等 isSameTree(p->left,q->left)
- 右子树也要相等 isSameTree(p->right,q->right)
/**
* Definition for a binary tree node.
* 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;
}
//一个为空,一个w不为空,就是x不相等的
if(p == NULL || q==NULL){
return false;
}
//递推
//当前值相等,左子树相等并且右子树相等
return p->val == q->val
&& isSameTree(p->left,q->left)
&& isSameTree(p->right,q->right);
}
对称二叉树
silu
- 根 p->val == q->val
- 左子树 isMirror(p->left , q->right)
- 右子树 isMirror(p->right,q->left)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isMirror(struct TreeNode *p,struct TreeNode *q){
if(p == NULL && q == NULL){
return true;
}
if(p == NULL || q == NULL){
return false;
}
return p->val == q->val
&& isMirror(p->left,q->right)
&& isMirror(p->right,q->left);
}
bool isSymmetric(struct TreeNode* root){
if(root == NULL){ //空树就是对称的
return true;
}
return isMirror(root->left,root->right);
}