AcWing 38. 二叉树的镜像
原题链接
简单
作者:
二叉树专题绝赞攻克中
,
2023-11-21 13:52:34
,
所有人可见
,
阅读 64
深度优先搜索解决
C++ 代码
/**
* 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:
void mirror(TreeNode* root) {
reverse(root);
}
void reverse(TreeNode* subroot){
//递归完成,每次传入根节点使其左右子树翻转
if(!subroot) return;
//swap
TreeNode* tmp;
if(!subroot->left && !subroot->right);
else{
// cout << "val值是" <<subroot->val<<"子树被改变了"<<endl;
tmp=subroot->left;
subroot->left=subroot->right;
subroot->right=tmp;
}
if(subroot->left) reverse(subroot->left);
if(subroot->right) reverse(subroot->right);
}
//问题1:子树没有传入
};