请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000
注意:本题与主站 226 题相同:https://leetcode-cn.com/problems/invert-binary-tree/
递归法
根据二叉树镜像的定义,考虑递归遍历(dfs)二叉树,交换每个节点的左 / 右子节点,即可生成二叉树的镜像。
递归解析:
终止条件: 当节点 root 为空时(即越过叶节点),则返回 null ;
递推工作:
初始化节点 temp ,用于暂存 root 的左子节点;
开启递归 右子节点 mirrorTree(root.right),并将返回值作为 root 的 左子节点 。
开启递归 左子节点 mirrorTree(temp) ,并将返回值作为 root 的 右子节点 。
返回值: 返回当前节点 root ;
Q: 为何需要暂存 root的左子节点?
A: 在递归右子节点 “root.left=mirrorTree(root.right);” 执行完毕后, root.left 的值已经发生改变,此时递归左子节点mirrorTree(root.left) 则会出问题。
/**
* 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 == nullptr)
{
return nullptr;
}
// left 和 right 反序, 临时保存left结点
TreeNode* temp = root->left;
root->left = mirrorTree(root->right);
root->right = mirrorTree(temp);
return root;
}
};
复杂度分析:
时间复杂度 O(N) : 其中 N 为二叉树的节点数量,建立二叉树镜像需要遍历树的所有节点,占用 O(N) 时间。
空间复杂度 O(N) : 最差情况下(当二叉树退化为链表),递归时系统需使用 O(N)大小的栈空间。
作者:ffreturn
链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/solution/cshuang-bai-de-di-gui-jie-fa-by-ffreturn-ostq/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。