题解 | #二叉树的镜像#
二叉树的镜像
https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7
class Solution {
public:
//一开始我的思路是用层序遍历+一个栈来反向构造。但一看通过率这么高就觉得应该不会这么复杂。再仔细一想,把整棵树都是镜像的问题分解到最小的子树也是镜像,这样就能解决了。因此就很简单了。
TreeNode* Mirror(TreeNode* pRoot) {
// write code here
if(pRoot==nullptr)
return nullptr;
if(pRoot->left==nullptr && pRoot->right==nullptr)
return pRoot;
swap(pRoot->left,pRoot->right);
Mirror(pRoot->left);
Mirror(pRoot->right);
return pRoot;
}
};
