NO18、二叉树的镜像(经典,可以再过一遍)
18、二叉树的镜像 可以再过一遍
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
1、借助队列来做,跟上面一题中的迭代版本很像
void Mirror(TreeNode* pRoot) {
if (pRoot == nullptr) return;
queue<TreeNode*> q;
q.push(pRoot);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node)
{
q.push(node->left);
q.push(node->right);
swap(node->left, node->right);
}
}
}
2、不使用swap函数的迭代版本
void Mirror(TreeNode* pRoot) {
if (pRoot == nullptr) return;
queue<TreeNode*> q;
q.push(pRoot);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node)
{
q.push(node->left);
q.push(node->right);
//swap(node->left, node->right);
TreeNode* temp = node->left;
node->left = node->right;
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
带你刷完67道剑指offer 文章被收录于专栏
- 本专栏汇集了67道剑指offer的一些精妙解法,不少题有5-6种解法之多,有些题目二刷三刷的解法也不一样。 - 本专栏帮助我拿到6个互联网大厂offer,最终圆梦字节跳动公司。
