首先要充分理解三种基本的递归遍历二叉树的方式
从这里可以思考递归函数的书写方式
226. 翻转二叉树
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return root;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
101. 对称二叉树
class Solution {
public:
bool compare(TreeNode* left, TreeNode* right) {
if (left && !right) {
return false;
}
else if (!left && right) {
return false;
}
else if (left && right && left->val != right->val) {
return false;
}
else if (!left && !right) {
return true;
}
bool boleft = compare(left->left, right->right);
bool bolright = compare(right->left, left->right);
return boleft && bolright;
}
bool isSymmetric(TreeNode* root) {
if (root == nullptr) return true;
return compare(root->left, root->right);
}
};
加油,努力继续学