原题目:https://leetcode-cn.com/problems/invert-binary-tree/
思路:
深度优先遍历,对每一个节点进行左右子树的翻转
进行深度优先遍历的时候,可以尝试不构造新的递归函数,这样比较省时间。
代码:
class Solution {
public:
void dfs(TreeNode* root){
if(root==NULL) return ;
TreeNode* t = root->left;
root->left = root->right;
root->right = t;
dfs(root->left);
dfs(root->right);
}
TreeNode* invertTree(TreeNode* root) {
dfs(root);
return root;
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == NULL) {
return NULL;
}
TreeNode* left = invertTree(root->left);
TreeNode* right = invertTree(root->right);
root->left = right;
root->right = left;
return root;
}
};