226. 翻转二叉树
二刷
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root)
return {};
invertTree(root->left);
invertTree(root->right);
std::swap(root->left, root->right);
return root;
}
};
这题的递归其实完全就是为了后序才递归的,递归本身并没有什么作用,连返回值都省略掉了。
三刷
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root)
return nullptr;
std::swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
前序也可以。但是中序要么遍历两次left要么两次right,因为中序会遍历到翻转后的结果。