题目大意:判断一颗二叉树是否对称
分析:dfs、bfs都可以
代码:dfs转载自https://www.cnblogs.com/xiaozhuyang/p/7376749.html
/**
* 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 isSymmetric(TreeNode* root) {
if(root == NULL)
return true;
return isSymmetric(root->left,root->right);
}
bool isSymmetric(TreeNode* left,TreeNode* right)
{
if(left == NULL && right == NULL) return true;
if(left == NULL || right == NULL) return false;
if(left->val != right->val)
return false;
return isSymmetric(left->left,right->right) && isSymmetric(left->right,right->left);
}
};
bfs转载自https://www.2cto.com/kf/201507/416787.html
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class
Solution {
public
:
bool isSymmetric(TreeNode *root) {
TreeNode *left, *right;
if
(!root)
return
true
;
queue<treenode*> q1, q2;
q1.push(root->left);
q2.push(root->right);
while
(!q1.empty() && !q2.empty()){
left = q1.front();
q1.pop();
right = q2.front();
q2.pop();
if
(NULL == left && NULL == right)
continue
;
if
(NULL == left || NULL == right)
return
false
;
if
(left->val != right->val)
return
false
;
q1.push(left->left);
q1.push(left->right);
q2.push(right->right);
q2.push(right->left);
}
return
true
;
}
};