题目分析:[[EVD]] - 剑指 Offer 27. 二叉树的镜像
https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/
简单描述:
- 输入一个二叉树,该函数输出它的镜像
限制🚫
- 0 <= 节点个数 <= 1000
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
解题思路:
思路:
- #BFS #DFS 遍历二叉树时交换每个节点的左右孩子节点
- 1.遍历交换
- 2.递归,利用三个参数的构造函数完成节点交换
效率:
- 时间复杂度
- 空间复杂度
代码:
- 1.遍历交换
class Solution { public: /*bfs遍历二叉树时交换每个节点的左右孩子节点*/ TreeNode *mirrorTree(TreeNode *root) { queue<TreeNode *> q; if (!root) return NULL; q.push(root); while (!q.empty()) { TreeNode *tmpT = q.front(); q.pop(); if (tmpT->right) q.push(tmpT->right); if (tmpT->left) q.push(tmpT->left); swap(tmpT->left, tmpT->right); } return root; } };
-
2.递归,利用构造函数简化代码class Solution { public: /*bfs遍历二叉树时交换每个节点的左右孩子节点*/ TreeNode* mirrorTree(TreeNode* root) { if (root == nullptr) return nullptr; TreeNode* tmp = root->left; root->left = mirrorTree(root->right); root->right = mirrorTree(tmp); return root; } };
class Solution
{
public:
/*
*dfs遍历二叉树时交换每个节点的左右孩子节点
*利用三个参数的构造函数完成节点交换
*TreeNode(int x, TreeNode* l, TreeNode* r) : val(x), left(l), right(r) {}
*/
TreeNode *mirrorTree(TreeNode *root)
{
return root == NULL ? NULL : new TreeNode(root->val, mirrorTree(root->right), mirrorTree(root->left));
}
};