思路:
递归交换节点的左右子树即可。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root) return {};
dfs(root);
return root;
}
void dfs(TreeNode* root){
if(!root) return;
auto tmp = root->left;
root->left = root->right;
root->right = tmp;
dfs(root->left);
dfs(root->right);
}
};
评论区