给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
解答:递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void helper(TreeNode* &root){
if(root == nullptr) return;
TreeNode* tmp;
tmp = root->left;
root->left = root->right;
root->right = tmp;
helper(root->left);
helper(root->right);
}
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) return root;
helper(root);
return root;
}
};