二叉树的翻转和对称二叉树的c++实现

1. 二叉树的翻转(镜像)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):
val(x), left(nullptr), right(nullptr) {
}
};
class Solution {
public:
void mirror(TreeNode* root) {
if (!root)
return;
if (!root->left && !root->right)
return;
TreeNode* tmp = root->left;
root->left = root->right;
root->right = root->left;
mirror(root->left);
mirrot(root->right);
}
};

2. 对称二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(nullptr), right(nullptr){
}
};
class Solution {
public:
bool isSymmetrical(TreeNode* root) {
if (!root)
return true;
bool res = helper(root->left, root->right);
return res;
}
bool helper(TreeNode* leftNode, TreeNode* rightNode) {
if (!leftNode && !rightNode)
return true;
if ((leftNode && !rightNode) || (!leftNode && rightNode))
return false;
if (leftNode->val != rightNode->val)
return false;
return helper(leftNode->left, rightNode->right) && helper(leftNode->right, rightNode->left);
}
};